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:

Java

Download

Output:

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 )

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz