How to Sort an Array in Java
The Challenge
Sort array elements in ascending or descending order!
Solutions
Method 1: Using Arrays.sort() - Ascending
import java.util.Arrays;
int[] numbers = {5, 2, 8, 1, 9};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
// Output: [1, 2, 5, 8, 9]Method 2: Descending Order (Using Collections)
import java.util.Arrays;
import java.util.Collections;
Integer[] numbers = {5, 2, 8, 1, 9};
Arrays.sort(numbers, Collections.reverseOrder());
System.out.println(Arrays.toString(numbers));
// Output: [9, 8, 5, 2, 1]Method 3: Using Java 8 Streams
import java.util.Arrays;
int[] numbers = {5, 2, 8, 1, 9};
int[] sorted = Arrays.stream(numbers).sorted().toArray();
System.out.println(Arrays.toString(sorted));
// Output: [1, 2, 5, 8, 9]Did You Know?
Arrays.sort() uses Dual-Pivot Quicksort for primitive types and TimSort for objects - both are highly optimized!
Pro Tip
Sort only a portion of the array:
int[] numbers = {5, 2, 8, 1, 9};
Arrays.sort(numbers, 1, 4); // Sort from index 1 to 3
// Result: [5, 1, 2, 8, 9]Real-World Use Cases
- Leaderboards: Sort scores
- E-commerce: Sort products by price
- Data analysis: Organize datasets
- Search algorithms: Binary search requires sorted arrays
›Short versionOpen if you only have a minute.
- Arrays.sort on an int array reorders that array. There is no new array.
- Anyone else holding the same reference sees the sorted order, including the caller.
- Sort a clone when the original order still matters.
- Printing the array with println shows a type and a hash. Arrays.toString shows the elements.
Sort an array
Reorder array elements into ascending or custom order.
Working approach
- Call Arrays.sort for the natural order of a primitive array.
- Clone first when this array is shared.
- For descending order, sort an Integer array with a comparator, or sort ascending and read backward. Collections.reverseOrder does not accept an int[].
Walk the sample
- Values 5, 1, 3
- sort reorders in place
- The same array is now 1, 3, 5
The trap
The sort looks like a query and is a mutation. A later search for the original position is looking at a different sequence.
int[] shared = {5, 2, 8, 1, 9};
int[] ordered = shared.clone();
Arrays.sort(ordered);
// shared is still {5, 2, 8, 1, 9}
// ordered is {1, 2, 5, 8, 9}After Arrays.sort(scores), what does the caller that passed scores still see?
The sorted array. sort writes into the same object.
If scores is a field or a parameter, every holder of that reference observes the new order. Clone before sorting when you still need the input order.
Primitive Arrays.sort is O(n log n) time and O(1) extra space aside from a small stack. Object sort is a stable O(n log n).
Easy to get wrong
- Sorting a shared array and then using it as if the order were unchanged.
- Printing the array reference instead of Arrays.toString.