Sort array of integers in Java (or any other primitive type)

In this article, we will discuss various methods to sort array of integers (or any other primitive type) in Java.


1. Sort array of integers using Arrays.sort()

Arrays class provides 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 Dual-Pivot Quicksort which is faster than traditional single-pivot Quicksort.


2. Sort array of integers using Arrays.parallelSort()

Java 8 also provides Arrays.parallelSort() which uses multiple threads for sorting as opposed to Arrays.sort() which uses only single thread to sort the elements. The threshold is calculated by considering the parallelism of the machine and size of the array. The ForkJoin common pool is used to execute any parallel tasks.

Below java program compares the performance of Arrays.sort() with Arrays.parallelSort() on huge data set of 10 million integers:




Arrays.sort() took 1763 ms
Arrays.parallelSort() took 801 ms


3. Sort array of integers using Java 8

We can also use Java 8 Stream API to sort an array of integers. 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.

References: Arrays (Java Platform SE 8 )

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of