Let’s learn Arrays.sort() in java.
Arrays.sort() in java
Arrays.sort() method is present in java.util.Arrays package. Arrays.sort() method sorts the specified range of the array into ascending order.
The range to be sorted extends from the index fromIndex, inclusive, to the index toIndex, exclusive. If fromIndex == toIndex, the range to be sorted is empty.
Syntax:
public static void sort(int[] a, int fromIndex, int toIndex)
Parameters:
a – array to be sorted
fromIndex – index of the first element to be sorted, inclusive.
toIndex – index of the last element to be sorted, exclusive.
sort() method do not return any value.
Throws:
IllegalArgumentException – if fromIndex > toIndex
ArrayIndexOutOfBoundsException – if fromIndex < 0 or toIndex > arr.length
Let’s see example on Arrays.sort() method in java.
import java.util.Arrays; public class ArraysSortExample { public static void main(String[] args) { int[] arrNum = {14, 5, 8, 23, 100, 85}; // arrays.sort // arrays.sort method by default sorts in ascending order Arrays.sort(arrNum); System.out.println(Arrays.toString(arrNum)); } }
Output:
[5, 8, 14, 23, 85, 100]
Now let’s learn how to sort a subarray of an array using sort() method.
import java.util.Arrays; public class SortSubarray { public static void main(String[] args) { int[] arrDemo = {14, 8, 5, 54, 41, 10, 1, 500}; // here we are sorting subarray elements only i.e, {8, 5, 54, 41} // arrays.sort Arrays.sort(arrDemo, 1, 5); System.out.println(Arrays.toString(arrDemo)); } }
Output:
[14, 5, 8, 41, 54, 10, 1, 500]
Sort array in java in descending order
Similarly let’s see java program to sort array in descending order. To sort array in descending order we need to provide external comparator which sorts array elements in reverse order.
In java we have built-in method reverseOrder() of Collections class. This method returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
import java.util.Arrays; import java.util.Collections; public class ArraySortDescending { public static void main(String[] args) { Integer[] arrNum = {14, 8, 5, 54, 41, 10, 1, 500}; // sort descending order // arrays.sort Arrays.sort(arrNum, Collections.reverseOrder()); System.out.println(Arrays.toString(arrNum)); } }
Output:
[500, 54, 41, 14, 10, 8, 5, 1]
Also read – variables in java