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.

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:

Download Code

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.

That’s all about sorting an array of integers in Java.

 
Reference: Arrays (Java Platform SE 21)