Arrays.sort() in Java: How to Sort an Array
Sorting an array is one of the most common tasks in Java development. The static Arrays.sort() method from the java.util.Arrays class sorts array elements in ascending order in place — fast, and without writing any sorting algorithm by hand. In this lesson you will learn how to sort an array in Java: the method’s overloads, sorting in descending order, sorting strings and objects, and how Arrays.sort() differs from Collections.sort().
Basic Example: Sorting in Ascending Order
The Arrays.sort() method sorts the elements of an array in ascending order:
import java.util.Arrays;
public class ArraysSortExample1 {
public static void main(String[] args) {
int[] array = new int[]{3, 1, 5, 6, 8};
Arrays.sort(array);
System.out.println(Arrays.toString(array));
}
}
Program output:
[1, 3, 5, 6, 8] Important
Arrays.sort() returns nothing (its return type is void) and modifies the original array. If you still need the original element order, make a copy first: int[] copy = Arrays.copyOf(array, array.length);
Overloads of Arrays.sort()
The java.util.Arrays class overloads sort() for every primitive type (except boolean) and for object arrays:
| Signature | What it sorts | Order |
|---|---|---|
sort(int[] a), sort(long[] a), sort(double[] a), etc. | An entire array of primitives | Ascending (natural order) |
sort(int[] a, int fromIndex, int toIndex) | A range of a primitive array | Ascending |
sort(Object[] a) | An array of objects implementing Comparable | Natural order (compareTo) |
sort(T[] a, Comparator<? super T> c) | An array of objects by a custom rule | Defined by the comparator (including descending) |
Under the hood
For primitives, Arrays.sort() uses Dual-Pivot Quicksort; for objects it uses TimSort, a stable variation of merge sort (since Java 7 — the «modified mergesort» description you may find in older articles is outdated). Both run in O(n log n) on average, so there is no reason to hand-write bubble sort in production code.
Sorting a Range of an Array
The overload with fromIndex and toIndex parameters sorts only the specified range. The start index is inclusive, the end index is exclusive:
import java.util.Arrays;
public class ArraysSortRangeExample {
public static void main(String[] args) {
int[] array = {9, 7, 5, 3, 1};
Arrays.sort(array, 1, 4); // sorts elements at indexes 1, 2, 3
System.out.println(Arrays.toString(array)); // [9, 3, 5, 7, 1]
}
}
If fromIndex > toIndex, the method throws an IllegalArgumentException; if the range goes beyond the array bounds, you get an ArrayIndexOutOfBoundsException.
Sorting an Array in Descending Order
To sort an array in descending order, use the overload that takes a comparator and pass Comparator.reverseOrder(). This overload works only with object arrays, so you need Integer[] instead of int[]:
import java.util.Arrays;
import java.util.Comparator;
public class ArraysSortDescExample {
public static void main(String[] args) {
Integer[] array = {3, 1, 5, 6, 8};
Arrays.sort(array, Comparator.reverseOrder());
System.out.println(Arrays.toString(array)); // [8, 6, 5, 3, 1]
}
}
A comparator cannot be applied to a primitive int[] array. Your options are:
- sort the array in ascending order, then reverse it with a loop (swap elements from both ends toward the middle);
- convert it with the Stream API:
int[] desc = Arrays.stream(array).boxed().sorted(Comparator.reverseOrder()).mapToInt(Integer::intValue).toArray();
Here is the sort-then-reverse approach:
int[] array = {3, 1, 5, 6, 8};
Arrays.sort(array); // [1, 3, 5, 6, 8]
for (int i = 0; i < array.length / 2; i++) {
int tmp = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = tmp;
}
System.out.println(Arrays.toString(array)); // [8, 6, 5, 3, 1]
Sorting Strings and Objects
An array of strings is sorted the same way as an array of numbers: String implements the Comparable interface, so the strings end up in lexicographic order:
String[] names = {"Olga", "Anna", "Boris"};
Arrays.sort(names);
System.out.println(Arrays.toString(names)); // [Anna, Boris, Olga]
For your own classes there are two options: implement Comparable in the class itself, or pass a Comparator as the second argument. Method references make comparators concise:
import java.util.Arrays;
import java.util.Comparator;
record Person(String name, int age) {}
public class ArraysSortObjectsExample {
public static void main(String[] args) {
Person[] people = {
new Person("Olga", 30),
new Person("Anna", 25),
new Person("Boris", 35)
};
Arrays.sort(people, Comparator.comparingInt(Person::age));
System.out.println(Arrays.toString(people));
// [Person[name=Anna, age=25], Person[name=Olga, age=30], Person[name=Boris, age=35]]
}
}
If the elements of an object array do not implement Comparable and no comparator is provided, a ClassCastException is thrown at runtime.
Arrays.sort() vs Collections.sort()
| Criteria | Arrays.sort() | Collections.sort() |
|---|---|---|
| What it sorts | Arrays: primitives and objects | Lists (List), objects only |
| Algorithm | Dual-Pivot Quicksort (primitives), TimSort (objects) | TimSort |
| Stability | Stable for objects; irrelevant for primitives | Stable |
| Descending order | Via Comparator (object arrays only) | Via Comparator or Collections.reverseOrder() |
Since Java 8, lists also have their own list.sort(comparator) method — Collections.sort() simply delegates to it internally.
Arrays.parallelSort()
Java 8 introduced Arrays.parallelSort() with the same set of overloads. It splits the array into chunks, sorts them in multiple threads using the Fork/Join pool, and merges the results. On large arrays (hundreds of thousands of elements or more) this pays off on multi-core CPUs; on small arrays parallelSort() falls back to a regular sequential sort, so you will not see any difference.
int[] bigArray = new int[1_000_000];
// ... fill the array ...
Arrays.parallelSort(bigArray);
Where Developers Get Tripped Up
- Expecting the method to return a new array.
Arrays.sort()returnsvoidand sorts in place — the lineint[] sorted = Arrays.sort(array);will not compile. - Passing a comparator for
int[]. TheComparatoroverload exists only for object arrays — useInteger[]or the Stream API instead. - Printing the array without
Arrays.toString().System.out.println(array)prints something like[I@1b6d3586— a hash, not the contents. - Forgetting about
nullelements. Sorting an object array containingnullthrows aNullPointerException; work around it withComparator.nullsFirst(...)orComparator.nullsLast(...). - Skipping the sort before
Arrays.binarySearch(). Binary search only works correctly on a sorted array — callingArrays.sort()first is mandatory.
Frequently Asked Questions
How do I sort an int[] array in descending order in Java?
Not directly: the Comparator overload works only with object arrays. Either use Integer[] with Comparator.reverseOrder(), sort the int[] in ascending order and reverse it with a loop, or use the Stream API with boxed() and sorted(Comparator.reverseOrder()).
Which sorting algorithm does Arrays.sort() use?
For primitive types it uses Dual-Pivot Quicksort; for object arrays it uses TimSort, a stable variation of merge sort. Both algorithms have an average time complexity of O(n log n).
What is the difference between Arrays.sort() and Collections.sort()?
Arrays.sort() sorts arrays, including arrays of primitives, while Collections.sort() sorts lists (List) of objects. Since Java 8, Collections.sort() internally delegates to list.sort(), which also uses TimSort.
Does Arrays.sort() return a new array?
No. The method is declared as void and modifies the given array in place. If you need to keep the original order, create a copy with Arrays.copyOf() first and sort the copy.
Comments