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

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

Syntax:

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

This method takes three arguments one of type byte 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 ArraysparallelSortbyterange {
    public static void main(String[] args) {

        byte a[] = { 12, 6, 6, 2, 4, 56, 23 };

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

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

Output:

[2, 6, 6, 12, 4, 56, 23]


Approach 2: IllegalArgumentException 

Java

import java.util.Arrays;

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

        byte a[] = { 12, 6, 6, 2, 4, 56, 23 };

        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:424)



Approach 3: ArrayIndexOutOfBoundsException

Java

import java.util.Arrays;

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

        byte a[] = { 12, 6, 6, 2, 4, 56, 23 };

        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:424)


No comments:

Post a Comment