Sort an array in Java
Categories:
Sorting Arrays in Java: A Comprehensive Guide

Learn various methods to sort arrays in Java, from built-in utilities to custom sorting logic, and understand their practical applications.
Sorting an array is a fundamental operation in computer science, crucial for optimizing search algorithms, presenting data clearly, and many other tasks. Java provides robust and efficient ways to sort arrays, catering to both primitive types and custom objects. This article will guide you through the most common and effective methods for sorting arrays in Java, including using the Arrays.sort()
method, implementing custom comparators, and understanding the underlying principles.
Sorting Primitive Arrays with Arrays.sort()
The simplest and most common way to sort primitive arrays (like int[]
, double[]
, char[]
, etc.) in Java is by using the static sort()
method from the java.util.Arrays
class. This method uses a highly optimized dual-pivot quicksort algorithm for primitive types, offering excellent performance for most use cases.
import java.util.Arrays;
public class PrimitiveArraySort {
public static void main(String[] args) {
int[] numbers = {5, 2, 8, 1, 9, 4};
System.out.println("Original array: " + Arrays.toString(numbers));
Arrays.sort(numbers);
System.out.println("Sorted array: " + Arrays.toString(numbers));
String[] names = {"Charlie", "Alice", "Bob"};
System.out.println("Original string array: " + Arrays.toString(names));
Arrays.sort(names);
System.out.println("Sorted string array: " + Arrays.toString(names));
}
}
Example of sorting primitive int
and String
arrays using Arrays.sort()
.
Arrays.sort()
method for primitive types sorts the array in ascending order by default. For String
arrays, it sorts lexicographically.Sorting Object Arrays with Arrays.sort()
and Comparable
When sorting arrays of objects, Java needs to know how to compare two objects. If your custom class implements the Comparable
interface, Arrays.sort()
can sort instances of that class naturally. The Comparable
interface requires implementing the compareTo()
method, which defines the natural ordering of objects.
import java.util.Arrays;
class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Person other) {
// Sort by age in ascending order
return Integer.compare(this.age, other.age);
}
}
public class ObjectArraySortComparable {
public static void main(String[] args) {
Person[] people = {
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
};
System.out.println("Original people array: " + Arrays.toString(people));
Arrays.sort(people);
System.out.println("Sorted people array (by age): " + Arrays.toString(people));
}
}
Sorting an array of custom Person
objects using the Comparable
interface.
Custom Sorting with Comparator
Sometimes, you need to sort objects based on criteria other than their natural ordering, or your class doesn't implement Comparable
. In such cases, you can use the Comparator
interface. Comparator
allows you to define multiple sorting strategies for the same class. The Arrays.sort()
method has an overloaded version that accepts a Comparator
as an argument.
flowchart TD A[Start] B{Is natural order sufficient?} C[Implement Comparable.compareTo()] D[Use Arrays.sort(array)] E{Need custom/multiple sort orders?} F[Create Comparator implementation] G[Use Arrays.sort(array, comparator)] H[End] A --> B B -- Yes --> C C --> D D --> H B -- No --> E E -- Yes --> F F --> G G --> H E -- No --> D
Decision flow for choosing between Comparable
and Comparator
for object sorting.
import java.util.Arrays;
import java.util.Comparator;
// Reusing the Person class from the previous example
// (assuming it might or might not implement Comparable)
public class ObjectArraySortComparator {
public static void main(String[] args) {
Person[] people = {
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35),
new Person("David", 25) // Added for tie-breaking example
};
System.out.println("Original people array: " + Arrays.toString(people));
// Sort by name in ascending order using a Comparator
Comparator<Person> nameComparator = new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return p1.getName().compareTo(p2.getName());
}
};
Arrays.sort(people, nameComparator);
System.out.println("Sorted by name: " + Arrays.toString(people));
// Sort by age, then by name for tie-breaking (using lambda for Comparator)
Comparator<Person> ageThenNameComparator = (p1, p2) -> {
int ageComparison = Integer.compare(p1.getAge(), p2.getAge());
if (ageComparison == 0) {
return p1.getName().compareTo(p2.getName()); // Tie-breaker by name
}
return ageComparison;
};
Arrays.sort(people, ageThenNameComparator);
System.out.println("Sorted by age then name: " + Arrays.toString(people));
}
}
Sorting an array of Person
objects using custom Comparator
implementations, including a lambda expression for chained sorting.
Comparator
can be implemented concisely using lambda expressions, making custom sorting logic much cleaner and more readable.