Arrays.parallelSort(char[], int, int) in Java

Arrays.parallelSort(char[], int, int): This method is available in java.util.Arrays class of Java.

Syntax:

void java.util.Arrays.parallelSort(char[] a, int fromIndex, int toIndex)

This method takes three arguments one of type char array and the rest two are of type int as its parameters. This method sorts the specified range of the array into ascending numerical order.

Parameters: Three parameters are required for this method.

a: the array to be sorted.

fromIndex: the index of the first element, inclusive, to be sorted.

toIndex: the index of the last element, exclusive, to be sorted.

Throws:

1. IllegalArgumentException - if fromIndex > toIndex.

2. ArrayIndexOutOfBoundsException - if fromIndex < 0 or toIndex > a.length.

Approach 1: When no exceptions

Java

import java.util.Arrays;

public class ArraysparallelSortcharrange {
    public static void main(String[] args) {

        char a[] = { 'a', 'd', 'c', 'e', 'p', 'o', 'q' };

        int fromIndex = 0, toIndex = 4;
        Arrays.parallelSort(a, fromIndex, toIndex);

        System.out.println(Arrays.toString(a));
    }
}

Output:

[a, c, d, e, p, o, q]


Approach 2: IllegalArgumentException

Java 

import java.util.Arrays;

public class ArraysparallelSortcharrange {
    public static void main(String[] args) {

        char a[] = { 'a', 'd', 'c', 'e', 'p', 'o', 'q' };

        int fromIndex = 5, toIndex = 4;
        Arrays.parallelSort(a, fromIndex, toIndex);

        System.out.println(Arrays.toString(a));
    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: fromIndex(5) > toIndex(4) at java.base/java.util.Arrays.rangeCheck(Arrays.java:718) at java.base/java.util.Arrays.parallelSort(Arrays.java:466)



Approach 3: ArrayIndexOutOfBoundsException

Java

import java.util.Arrays;

public class ArraysparallelSortcharrange {
    public static void main(String[] args) {

        char a[] = { 'a', 'd', 'c', 'e', 'p', 'o', 'q' };

        int fromIndex = -1, toIndex = 4;
        Arrays.parallelSort(a, fromIndex, toIndex);

        System.out.println(Arrays.toString(a));
    }
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: -1 at java.base/java.util.Arrays.rangeCheck(Arrays.java:722) at java.base/java.util.Arrays.parallelSort(Arrays.java:466)



No comments:

Post a Comment