How to sort elements in Byte Array using Index in Java?
Declaration :
1 |
public static void sort(byte[] a, int fromIndex, int toIndex) |
Explanation :
Purpose | The java.util.Arrays.sort(byte[] a int fromIndex int toIndex) method sorts the specified range of the specified array of bytes into ascending numerical order. The range to be sorted extends from index fromIndex inclusive to index toIndex exclusive. |
Parameters | a ===> This is the array to be sorted. |
fromIndex ===> This is the index of the first element (inclusive) to be sorted. | |
toIndex ===> This is the index of the last element (exclusive) to be sorted . | |
Return Value | This method does not return any value. |
Exception | IllegalArgumentException — if fromIndex > toIndex ,ArrayIndexOutOfBoundsException — if fromIndex < 0 or toIndex > a.length |
Java Program : Example
Below example will explain java.util.Arrays.sort() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package com.c4learn; import java.util.Arrays; public class ArrayDemo { public static void main(String[] args) { // Initialize unsorted byte array byte arr[] = { 10, 40, 20, 50, 30 }; // Print the Unsorted Array List System.out.println("The Unsorted Byte Array list is:"); for (byte num : arr) { System.out.println("Array Element is " + num); } // Sort the Byte Array List Arrays.sort(arr, 0, 5); // Print the Sorted Byte Array List System.out.println("The Sorted Byte array is:"); for (byte num : arr) { System.out.println("Array Element is " + num); } } } |
Output of Program :
1 2 3 4 5 6 7 8 9 10 11 12 |
The Unsorted Byte Array list is: Array Element is 10 Array Element is 40 Array Element is 20 Array Element is 50 Array Element is 30 The Sorted Byte array is: Array Element is 10 Array Element is 20 Array Element is 30 Array Element is 40 Array Element is 50 |