Java sort array Example
1. Introduction
Java Arrays.sort() method is a method of the java.util.Arrays class which is used to sort an array passed to it as a parameter either in ascending order or in order of user-defined type.
2. Arrays.sort() method
Table displaying the different overloaded forms of Arrays.sort() method.
Method Syntax | Description | Parameters | Exception |
static void sort(byte[] a) | Sorts the specified array into ascending numerical order. | a – the array to be sorted | |
static void sort(byte[] a, int fromIndex, int to Index) | 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. | a – the array to be sortedfromIndex – the index of the first element, inclusivetoIndex – the index of the last element, exclusive | IllegalArgumentException – if fromIndex > toIndex ArrayIndexOutOfBoundsException – if fromIndex < 0 or toIndex > a.length |
static void sort(char[] a) | Sorts the specified array into ascending numerical order. | a – the array to be sorted | |
static void sort(char[] a, int fromIndex, int to Index) | 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. | a – the array to be sortedfromIndex – the index of the first element, inclusivetoIndex – the index of the last element, exclusive | IllegalArgumentException – if fromIndex > toIndex ArrayIndexOutOfBoundsException – if fromIndex < 0 or toIndex > a.length |
static void sort(double[] a) | Sorts the specified array into ascending numerical order. The < relation does not provide a total order on all double values: -0.0d == 0.0d is true and a Double.NaN value compares neither less than, greater than, nor equal to any value, even itself. | a – the array to be sorted | |
static void(double[] a, int fromIndex, int to Index ) | 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. The < relation does not provide a total order on all double values: -0.0d==0.0d is true and a Double.NaN value compares neither less than, greater than, nor equal to any value, even itself. | a – the array to be sortedfromIndex – the index of the first element, inclusivetoIndex – the index of the last element, exclusive | IllegalArgumentException – if fromIndex > toIndex ArrayIndexOutOfBoundsException – if fromIndex < 0 or toIndex > a.length |
static void sort(float[] a) | Sorts the specified array into ascending numerical order. The < relation does not provide a total order on all float values: -0.0f == 0.0f is true and a Float.NaN value compares neither less than, greater than, nor equal to any value, even itself. | a – the array to be sorted | |
static void sort(float[] a, int fromIndex, int toIndex) | 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. The < relation does not provide a total order on all float values: -0.0f == 0.0f is true and a Float.NaN value compares neither less than, greater than, nor equal to any value, even itself. | a – the array to be sortedfromIndex – the index of the first element, inclusivetoIndex – the index of the last element, exclusive | IllegalArgumentException – if fromIndex > toIndex ArrayIndexOutOfBoundsException – if fromIndex < 0 or toIndex > a.length |
static void sort(int[] a) | Sorts the specified array into ascending numerical order. | a – the array to be sorted | |
static void sort(int[] a, int fromIndex, int toIndex ) | 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. | a – the array to be sortedfromIndex – the index of the first element, inclusivetoIndex – the index of the last element, exclusive | IllegalArgumentException – if fromIndex > toIndex ArrayIndexOutOfBoundsException – if fromIndex < 0 or toIndex > a.length |
static void sort(long[] a) | Sorts the specified array into ascending numerical order. | a – the array to be sorted | |
static void sort(long[] a, int fromIndex, int toIndex) | Sorts the specified range of the array into ascending order. The range to be sorted extends from the index fromIndex , inclusive, to the index, exclusive. If fromIndex == toIndex , the range to be sorted is empty. | a – the array to be sortedfromIndex – the index of the first element, inclusivetoIndex – the index of the last element, exclusive | IllegalArgumentException – if fromIndex > toIndex ArrayIndexOutOfBoundsException – if fromIndex < 0 or toIndex > a.length |
static void sort(Object[] a) | Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. All elements in the array must implement the Comparable interface. Furthermore, all elements in the array must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array). | a – the array to be sorted | ClassCastException – if the array contains elements that are not mutually comparable (for example, strings and integers)IllegalArgumentException – (optional) if the natural ordering of the array elements is found to violate the Comparable contract |
static void sort(Object[] a, int fromIndex, int toIndex) | Sorts 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). | a – the array to be sortedfromIndex – the index of the first element (inclusive)toIndex – the index of the last element (exclusive) | IllegalArgumentException – if fromIndex > toIndex or (optional) if the natural ordering of the array elements is found to violate the Comparable contractArrayIndexOutOfBoundsException – if fromIndex < 0 or toIndex > a.length ClassCastException – if the array contains elements that are not mutually comparable (for example, strings and integers). |
static void sort(short[] a) | Sorts the specified array into ascending numerical order. | a – the array to be sorted | |
static void sort(short[] a, int fromIndex, int toIndex) | 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. | a – the array to be sortedfromIndex – the index of the first element, inclusivetoIndex – the index of the last element, exclusive | IllegalArgumentException – if fromIndex > toIndex ArrayIndexOutOfBoundsException – if fromIndex < 0 or toIndex > a.length |
public static <T> void sort(T[] a, Comparator<? super T> c) | Sorts the specified array of objects according to the order induced by the specified comparator. All elements in the array must be mutually comparable by the specified comparator (that is, c.compare(e1,e2) must not throw a ClassCastException for any elements e1 and e2 in the array). | a – the array to be sortedc – the comparator to determine the order of the array. A null value indicates that the elements’ natural ordering should be used. | ClassCastException – if the array contains elements that are not mutually comparable using the specified comparatorIllegalArgumentException – (optional) if the comparator is found to violate the Comparator contract |
public static <T> void sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c) | Sorts the specified range of the specified array of objects according to the order induced by the specified comparator. 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 the range must be mutually comparable by the specified comparator (that is, c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the range). | a – the array to be sortedfromIndex – the index of the first element (inclusive) toIndex – the index of the last element (exclusive) c – the comparator to determine the order of the array. A null value indicates that the elements’ natural ordering should be used. | ClassCastException – if the array contains elements that are not mutually comparable using the specified comparator.IllegalArgumentException – if fromIndex > toIndex or (optional) if the comparator is found to violate the Comparator contractArrayIndexOutOfBoundsException – if fromIndex < 0 or toIndex > a.length |
3. Arrays.sort() method examples
The following examples show the usage of different forms of the sort() method.
SortDemo.java
import java.util.Arrays; import java.util.*; public class Main{ public static void main(String []args){ // Our arr contains 8 elements int[] arr = {36,23,32,25,66,79,102,53}; // sorting the integer array in ascending order. Arrays.sort(arr); System.out.printf("Sorted Array : \n%s\n\n", Arrays.toString(arr)); // Sorting the integer array from index 1 to 4 i.e. elements 23,32,25 and 66 only. // only sort subarray {23,32,25,66} Arrays.sort(arr,1,5); System.out.printf("Sorted Array: \n%s\n\n", Arrays.toString(arr)); //We are using Integer array as Collections.reverseOrder() method won't work with primitive types. Integer[] arr1 = {36,23,32,25,66,79,102,53}; // Sorting Integer array in descending order Arrays.sort(arr1, Collections.reverseOrder()); System.out.printf("Sorted Array : \n%s\n\n", Arrays.toString(arr1)); // String arr2[] = {"Hello Everyone!!", "Let's get it done !", "Work Done, let's break out." }; // Sorts String array in ascending order Arrays.sort(arr2); System.out.printf("Sorted Array: \n%s\n\n", Arrays.toString(arr2)); // Sorts String array in descending order Arrays.sort(arr2, Collections.reverseOrder()); System.out.printf("Sorted Array: \n%s\n\n", Arrays.toString(arr2)); } }
Output
Sorted Array: [23, 25, 32, 36, 53, 66, 79, 102] Sorted Array : [102, 79, 66, 53, 36, 32, 25, 23] Sorted Array: [Hello Everyone!!, Let's get it done !, Work Done, let's break out.] Sorted Array: [Work Done, let's break out., Let's get it done !, Hello Everyone!!]
CustomSortDemo.java
// Java program to demonstrate working of Comparator // interface import java.util.*; import java.io.*; // A class to represent an Employee. class Employee { int empid; String name, address; // Constructor public Employee(int empid, String name, String address) { this.empid = empid; this.name = name; this.address = address; } // Used to print employee details in main() public String toString() { return this.empid + " " + this.name + " " + this.address; } } class SortbyEmpId implements Comparator { // Used for sorting in ascending order of // empid public int compare(Employee a, Employee b) { return a.empid - b.empid; } } // Driver class class Main { public static void main (String[] args) { Employee [] arr = {new Employee(111, "Ajit", "Washington"), new Employee(131, "Shammy", "NewYork"), new Employee(121, "Jyoti", "Bangalore")}; System.out.println("Unsorted"); for (int i=0; i<arr.length; i++) System.out.println(arr[i]); Arrays.sort(arr, new SortbyEmpId()); System.out.println("\nSorted by empid"); for (int i=0; i<arr.length; i++) System.out.println(arr[i]); } }
Unsorted 111 Ajit Washington 131 Shammy NewYork 121 Jyoti Bangalore Sorted by empid 111 Ajit Washington 121 Jyoti Bangalore 131 Shammy NewYork
4. Arrays.sort vs Collections.sort
The below table lists the differences between Arrays.sort() method and Collections.sort method.
Serial No. | Arrays.sort() | Collections.sort() |
1. | Used to sort an array of primitive data types as well as objects. | used to sort Collections like Lists and Sets etc. |
2. | It uses dual-pivot Quicksort for Primitive Arrays and MergeSort for sorting an array of Objects. | Internally it uses Arrays.sort() method only |
3. | Operates on objects that are in contiguous memory locations | Operates on objects that are either in continuous or in discrete memory locations |
4. | It doesn’t create an extra copy of the original arrays. | It always creates an extra copy of the original list objects to maintain mutability. |
5. Java sort array – Conclusion
In this tutorial, we saw the different forms of Arrays.sort() with certain examples to demonstrate their usage in different situations. Moreover, we also understood the difference between Arrays.sort() and Collections.sort() method.
6. References
- https://www.geeksforgeeks.org/arrays-sort-in-java-with-examples/
- https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html
- https://stackoverflow.com/questions/5208133/collections-vs-arrays-regarding-sort
7. Download the source code
This was an example of the Java sort array method.
You can download the full source code of this example here: Java sort array Example