Sort array of integers in Java (or any other primitive type)
This article will discuss various methods to sort a primitive integer array (or any other primitive type) in Java.
1. Sort integer array using Arrays.sort() method
Arrays class provides a sort() method for sorting primitive arrays. It sorts the specified array of primitives types into ascending order, according to the natural ordering of its elements. It uses a dual-pivot Quicksort, which is faster than the traditional single-pivot Quicksort.
|
1 2 3 |
int[] a = { 4, 2, 1, 5, 3 }; Arrays.sort(a); System.out.println(Arrays.toString(a)); // [1, 2, 3, 4, 5] |
2. Sort integer array using Arrays.parallelSort() method
Java 8 also provides Arrays.parallelSort(), which uses multiple threads for sorting instead of Arrays.sort(), which uses only a single thread to sort the elements. The threshold is calculated by considering the parallelism of the machine and the size of the array. The ForkJoin common pool is used to execute any parallel tasks. Following Java program compares the performance of Arrays.sort() with Arrays.parallelSort() on a huge data set of 10 million integers:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import java.util.Arrays; import java.util.Random; class Main { private static final int len = 10000000; public static void main(String[] args) { // create two arrays of integers of size 10 million int[] arr1 = new int[len]; int[] arr2 = new int[len]; // Assign random values to `arr1[]` and `arr2[]` Random r = new Random(); for (int i = 0; i < len; i++) { arr1[i] = r.nextInt(); arr2[i] = arr1[i]; } long start = System.currentTimeMillis(); // sort `arr1[]` using `Arrays.sort()` Arrays.sort(arr1); long end = System.currentTimeMillis(); System.out.println("Arrays.sort() took " + (end - start) + " ms"); start = System.currentTimeMillis(); // sort `arr2[]` using `Arrays.parallelSort()` Arrays.parallelSort(arr2); end = System.currentTimeMillis(); System.out.println("Arrays.parallelSort() took " + (end - start) + " ms"); } } |
Output:
Arrays.sort() took 1763 ms
Arrays.parallelSort() took 801 ms
3. Sort integer array using Stream API
We can also use Java 8 Stream API to sort a primitive integer array. The idea is to get IntStream from elements of the specified array and sort it according to natural order or in reverse order using a comparator. Finally, we convert the sorted stream back to the integer array.
|
1 2 3 |
int[] arr = { 5, 4, 3, 2, 1 }; arr = Arrays.stream(arr).sorted().toArray(); System.out.println(Arrays.toString(arr)); // [1, 2, 3, 4, 5] |
That’s all about sorting an array of integers in Java.
Reference: Arrays (Java Platform SE 21)
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)