Java Utility Library

Java Arrays - parallelSort() Method



The java.util.Arrays.parallelSort() method is used to sort the specified range of the specified array of objects into ascending order, according to the natural ordering of its elements. The range to be sorted extends from index fromIndex, inclusive, to index toIndex, exclusive. (If fromIndex==toIndex, the range to be sorted is empty.) All elements in this range must implement the Comparable interface. Furthermore, all elements in this range must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array).

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

Syntax

public static <T extends Comparable<? super T>> void parallelSort(T[] a,
                                                                  int fromIndex,
                                                                  int toIndex)

Here, T is the type of elements in the array.


Parameters

a Specify the array to be sorted.
fromIndex Specify the index of the first element (inclusive) to be sorted.
toIndex Specify the index of the last element (exclusive) to be sorted.

Return Value

void type.

Exception

  • Throws ClassCastException, if the array contains elements that are not mutually comparable (for example, strings and integers).
  • Throws IllegalArgumentException, if fromIndex > toIndex or (optional) if the natural ordering of the array elements is found to violate the Comparable contract.
  • Throws ArrayIndexOutOfBoundsException, if fromIndex < 0 or toIndex > a.length.

Example:

In the example below, the java.util.Arrays.parallelSort() method is used to sort a specified range of the specified array of objects.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating an unsorted Integer array
    Integer Arr[] = {10, 2, -3, 35, 56, 25};

    //printing array before sorting
    System.out.print("Arr contains:"); 
    for(Integer i: Arr)
      System.out.print(" " + i);

    //sort the array for range [1,5)
    Arrays.sort(Arr, 1, 5);

    //printing array after sorting
    System.out.print("\nArr contains:"); 
    for(Integer i: Arr)
      System.out.print(" " + i);   
  }
}

The output of the above code will be:

Arr contains: 10 2 -3 35 56 25
Arr contains: 10 -3 2 35 56 25

❮ Java.util - Arrays