Arrays.sort() in Java with Examples

Arrays.sort() in Java with Examples | In this post, we will discuss how to sort an array using Arrays.sort() in Java? What is the efficient way to sort Java arrays? How to use Arrays.sort() method in Java? How to use Arrays.parallelSort() in Java? What are the differences between the Java method Arrays.sort() and Arrays.parallelSort()?

There are many sorting algorithms are available to solve only one problem i.e. sort an array. They have different time complexity and space complexity. But among all sorting algorithms Quick Sort gives the best performance. 

The time complexity of Quicksort is O(n log n) in the best case, O(n log n) in the average case, and O(n^2) in the worst case. But because it has the best performance in the average case for most inputs, Quicksort is generally considered the “fastest” sorting algorithm.

In the java.util.Arrays class there are several sort() methods are available. All of them use dual-pivot Quicksort. The Dual-Pivot Quicksort is given by Vladimir Yaroslavskiy, Jon Bentley, and Josh Bloch. This algorithm offers O(n log(n)) performance on all data sets and is typically faster than traditional (one-pivot) Quicksort implementations.

Dual pivot quicksort is a little bit faster than the original single-pivot quicksort. But still, the worst case will remain O(n^2) when the array is already sorted in an increasing or decreasing order. 

Note:- While working with Java arrays, no need to write your own logic to implement any sorting algorithm. Just import the Arrays class and use the Arrays.sort() in Java which gives the best performance in most cases compared to other sorting algorithms.

In Arrays class there are several overloaded sort() methods are available. These are,

  1. public static void sort(byte[] a)
  2. public static void sort(short[] a)
  3. public static void sort(int[] a)
  4. public static void sort(long[] a)
  5. public static void sort(float[] a)
  6. public static void sort(double[] a)
  7. public static void sort(char[] a)
  8. public static void sort(Object[] a)
  9. public static void sort(byte[] a, int fromIndex, int toIndex)
  10. public static void sort(short[] a, int fromIndex, int toIndex)
  11. public static void sort(int[] a, int fromIndex, int toIndex)
  12. public static void sort(long[] a, int fromIndex, int toIndex)
  13. public static void sort(float[] a, int fromIndex, int toIndex)
  14. public static void sort(double[] a, int fromIndex, int toIndex)
  15. public static void sort(char[] a, int fromIndex, int toIndex)
  16. public static void sort(Object[] a, int fromIndex, int toIndex)

Arrays.sort(array):- It sorts the full array into ascending order.
Arrays.sort(array, fromIndex, toIndex):- It sorts only the elements from fromIndex to toIndex.

Program to Sort array using Arrays.sort() in Java

Let us demonstrate an example of sorting an array using the Arrays.sort() in Java.

import java.util.Arrays;

public class SortArray {
  
  // main method
  public static void main(String[] args) {

    // declare and initialize arrays
    int arr[] = {50, 25, 30, 55, 15};
    
    // display array before sorting
    System.out.println("Before Sorting: " + Arrays.toString(arr));
    
    // sort array
    Arrays.sort(arr);
    
    // display array after sorting
    System.out.println("After Sorting: " + Arrays.toString(arr));
  }
}

Output:-

Before Sorting: [50, 25, 30, 55, 15]
After Sorting: [15, 25, 30, 50, 55]

Now, let us demonstrate the byte, short, long, float, double, char, boolean array.

Sort array of bytes using Arrays.sort() in Java,

// byte array
byte[] byteArr = {15, 12, 11, 14, 13};
Arrays.sort(byteArr);
System.out.println("Byte Array = " + Arrays.toString(byteArr));

Byte Array = [11, 12, 13, 14, 15]

Sort array of shorts using Arrays.sort() in Java,

// short array
short[] shortArr = {400, 200, 100, 300, 500};
Arrays.sort(shortArr);
System.out.println("Short Array = " + Arrays.toString(shortArr));

Short Array = [100, 200, 300, 400, 500]

Sort array of longs using Arrays.sort() in Java,

// long array
long[] longArr = {999999999, 10, 500, -888888888, 0};
Arrays.sort(longArr);
System.out.println("Long Array = " + Arrays.toString(longArr));

Long Array = [-888888888, 0, 10, 500, 999999999]

Sort array of floats using Arrays.sort() in Java,

// float array
float[] floatArr = {15.9f, 10.5f, 500, -88888, 0.9f};
Arrays.sort(floatArr);
System.out.println("Float Array = " + Arrays.toString(floatArr));

Float Array = [-88888.0, 0.9, 10.5, 15.9, 500.0]

Sort array of doubles using Arrays.sort() in Java,

// double array
double[] doubleArr = {10.5, 15.9, 500, -88888, 0.9};
Arrays.sort(doubleArr);
System.out.println("Double Array = " + Arrays.toString(doubleArr));

Double Array = [-88888.0, 0.9, 10.5, 15.9, 500.0]

Sort array of chars using Arrays.sort() in Java,

// char array
char[] charArr = {'K','n','o','w','P','r','o','g','r',97,'m'};
Arrays.sort(charArr);
System.out.println("Char Array = " + Arrays.toString(charArr));

Char Array = [K, P, a, g, m, n, o, o, r, r, w]

The sorting operation is not applicable to boolean values. The boolean value can contain either true or false. Therefore, the Arrays class doesn’t contain any method to sort the boolean array. The below code gives an error.

// boolean array
boolean[] boolArr = {true, false, true, true, false};
Arrays.sort(boolArr); // error

If the specified array is referenced to null then also the Arrays.sort() in Java doesn’t give any error or exception.

int arr[] = null;
Arrays.sort(arr); // valid

Sorting Example using Arrays.sort(array, fromIndex, toIndex)

Using Arrays.sort(array, fromIndex, toIndex) in Java, we can sort only the elements between a particular range. Here fromIndex is the index of the first element, inclusive, to be sorted, and toIndex is the index of the last element, exclusive, to be sorted. 

  • fromIndex:- index of the first element, inclusive.
  • toIndex:- index of the last element, exclusive.
import java.util.Arrays;

public class SortArray {
  
  // main method
  public static void main(String[] args) {

    // declare and initialize arrays
    int arr[] = {50, 25, 30, 55, 15};
    
    // display array before sorting
    System.out.println("Before Sorting: " + Arrays.toString(arr));
    
    // sort array
    Arrays.sort(arr, 0, 3);
    
    // display array after sorting
    System.out.println("After Sorting: " + Arrays.toString(arr));
  }
}

Output:-

Before Sorting: [50, 25, 30, 55, 15]
After Sorting: [25, 30, 50, 55, 15]

Let us see some more example with Arrays.sort(array, fromIndex, toIndex)

// char array
char[] charArr1 = {'k','n','o','w','p','r','o','g','r','a','m'};
// sort only {'p','r','o','g','r',97,'m'}
Arrays.sort(charArr1, 4, charArr1.length);
System.out.println("Char Array = " + Arrays.toString(charArr1));

Char Array = [k, n, o, w, a, g, m, o, p, r, r]

// char array
char[] charArr2 = {'k','n','o','w','p','r','o','g','r','a','m'};
// sort only {'n','o','w,,'p','r','o'}
Arrays.sort(charArr2, 1, 7);
System.out.println("Char Array = " + Arrays.toString(charArr2));

Char Array = [k, n, o, o, p, r, w, g, r, a, m]

Exceptions thrown by Arrays.sort(array, fromIndex, toIndex) in Java

  • IllegalArgumentException:- if fromIndex > toIndex
  • ArrayIndexOutOfBoundsException:- if fromIndex < 0 or toIndex > a.length
int arr[] = {50, 25, 30, 55, 15};
Arrays.sort(arr, 5, 0);

Exception in thread “main” java.lang.IllegalArgumentException: fromIndex(5) > toIndex(0)

int arr[] = {50, 25, 30, 55, 15};
Arrays.sort(arr, -9, 5);

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Array index out of range: -9

int arr[] = {50, 25, 30, 55, 15};
Arrays.sort(arr, 0, 7);

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 7

Arrays.parallelSort() in Java

The java.util.Arrays class also contains parallelSort() method to sort an array. It also sorts the specified array into ascending numerical order. It is added in Java8.

Similarity with Arrays.parallelSort() and Arrays.sort() in Java

  • Both can be used to sort objects and primitive arrays.
  • By default, both method sorts an array into ascending order.

Unlike Arrays.sort() in Java (which is based on a single thread), It uses multiple threads. And for executing parallel tasks it uses the ForkJoin pool. It uses a sort-merge technique that divides the specified array into chunks of some size and sorts each chunk individually. Finally, the sorted chunks are merged using the merge logic from the Merge-sort algorithm.

The implementation in JDK 8 uses this approach:
1) Divide the array into 4 parts.
2) Sort the first two parts and then merge them.
3) Sort the next two parts and then merge them.

The above steps are repeated recursively with each part until the size of the part to sort is not lesser than the threshold value calculated above.

Note:- Arrays.parallelSort() in Java uses parallelism only when certain conditions are met. If the array size is less than or equal to 8192 or the processor has only one core, then it internally uses the Arrays.sort() method.

Similar to Arrays.sort() in Java, it also has two variants to sort a full array and partial array,

  • Arrays.parallelSort(array):- It sorts the full array into ascending order.
  • Arrays.parallelSort(array, fromIndex, toIndex):- It sorts only the elements from fromIndex to toIndex.
import java.util.Arrays;

public class CompareArray {
  
  // main method
  public static void main(String[] args) {

    // declare and initialize arrays
    int arr[] = {50, 30, 25, 55, 15};
    
    // sort array
    Arrays.parallelSort(arr);
    
    // display array after sorting
    System.out.println(Arrays.toString(arr));
  }
}

Output:-

[15, 25, 30, 50, 55]

Another example is to sort array only the particular elements from fromIndex to toIndex,

// declare and initialize arrays
int arr[] = {50, 30, 25, 55, 15};
    
// sort array using parallelSort()
Arrays.parallelSort(arr, 1, 3);
    
// display array after sorting
System.out.println(Arrays.toString(arr));

Output:-

[50, 25, 30, 55, 15]

Arrays.sort() in Java vs Arrays.parallelSort() 

Arrays.sort()Arrays.parallelSort()
To perform the operation, it uses a single thread. Therefore sorting is done sequentially i.e. the whole array is sorted using a single thread.To perform the operation, it uses multiple threads. The sorting is done in parallel. i.e. several threads execute in parallel to sorts the chunk of the array.
It is faster for smaller array sizes, but gives less performance for large datasets and takes a bit longer time to perform the operation.It is slower for smaller data sets but gives better performance for large-size arrays.
It doesn’t utilize the multiple cores of the system.It utilizes the multiple cores of the system.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *