You must have worked in Arrays and here I will explain various ways of how to sort array in java.
Java Array is primitive type of collection of objects which are of same type. In simple ways we can define it as a container having same types of items in it. Java Array holds fixed number of items which are defined at the time of declaration.
Sort Array in Java
Quite often we need to sort an array in java. Below is the sample example for sorting array of integers.
// A sample Java program to sort an array of integers // using Arrays.sort(). It by default sorts in ascending order import java.util.Arrays; public class ArraySortExample { public static void main(String[] args) { // Our arr contains 5 elements int[] arr = {45,102,85,7,64}; Arrays.sort(arr); System.out.printf("Sorted Array : %s", Arrays.toString(arr)); } } Output: Sorted Array : [7,45,64,85,102]
Important Points to consider
- We use Arrays.sort(T[] arr) if the array type implements Comparable interface.
- There is another type of Arrays.sort(T[] arr, Comparator c) method which can be used to sort custom object array based on various fields.
- Arrays.sort(T[] t) uses Quicksort algorithm having performance of O(n log(n)). This sorts in natural ascending order.
Sort Sub-Array within the Array
package com.techblogstation; import java.util.Arrays; public class SortSubArrayExample { public static void main(String[] args) { int[] arr = {35, 71, 16, 4, 21, 90, 2, 22}; // Sort subarray from index 1 to 4, i.e., // only sort subarray {71, 16, 4, 21} and // It will keep other elements as it is. Arrays.sort(arr, 1, 5); System.out.printf("Sorted Sub-Array : %s", Arrays.toString(arr)); } } Output: Sorted Sub-Array : [35, 4, 16, 21, 71, 90, 2, 22]
Sort Array in descending order
Program for sorting array in descending order.
package com.techblogstation; import java.util.Arrays; import java.util.Collections; public class SortDescExample { public static void main(String[] args) { Integer[] arr = {45,78,95,102,68,71,24}; // Sorts arr[] in descending order Arrays.sort(arr, Collections.reverseOrder()); System.out.printf("Modified array : %s", Arrays.toString(arr)); } } Output:- Modified array : [102, 95, 78, 71, 68, 45, 24]
Sort Array of strings in alphabetical order
A sample Java program to sort an array of strings in ascending and descending orders using Arrays.sort().
package com.techblogstation; import java.util.Arrays; import java.util.Collections; public class SortStringExample { public static void main(String[] args) { String arr[] = {"Rahul","Anil","Amit","Sanjeev"}; // Sorts arr[] in ascending order Arrays.sort(arr); System.out.printf("Array in ascending order : \n%s\n\n", Arrays.toString(arr)); // Sorts arr[] in descending order Arrays.sort(arr, Collections.reverseOrder()); System.out.printf("Array in descending order : \n%s\n\n", Arrays.toString(arr)); } } Output:- Array in ascending order : [Amit, Anil, Rahul, Sanjeev] Array in descending order : [Sanjeev, Rahul, Anil, Amit]
Sort an array according to custom defined object criteria
In this example first we will create a Employee class for which we will make objects and store in array.
package com.techblogstation; public class Employee { private int empId; private String name; private int age; Employee(int empId,String name, int age) { this.age=age; this.name=name; this.empId=empId; } public int getEmpId() { return empId; } public void setEmpId(int empId) { this.empId = empId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Employee [empId=" + empId + ", name=" + name + ", age=" + age + "]"; } }
Now we will create two classes which will implement Comparator interface and will override the method compare(Object o1,Object o2).
package com.techblogstation; import java.util.Comparator; public class SortByAge implements Comparator<Employee> { // Used for sorting in ascending order of age public int compare(Employee e1, Employee e2) { return e1.getAge() - e2.getAge(); } } package com.techblogstation; import java.util.Comparator; public class SortByName implements Comparator<Employee> { // Used for sorting in ascending order of name public int compare(Employee e1, Employee e2) { return e1.getName().compareTo(e2.getName()); } }
Now we will create a driver main class in which Array.sort() method will be used by passing the custom comparator method.
package com.techblogstation; import java.util.Arrays; public class DriverClass { public static void main(String args[]) { Employee[] arr = { new Employee(111, "Emp1", 20), new Employee(131, "Emp4", 18), new Employee(121, "Emp2", 30) }; System.out.println("Unsorted"); for (int i = 0; i < arr.length; i++) System.out.println(arr[i]); Arrays.sort(arr, new SortByAge()); System.out.println("\nSorted by Age"); for (int i = 0; i < arr.length; i++) System.out.println(arr[i]); System.out.println("\nSorted by Name"); Arrays.sort(arr, new SortByName()); for (int i = 0; i < arr.length; i++) System.out.println(arr[i]); } } Output:- Unsorted Employee [empId=111, name=Emp1, age=20] Employee [empId=131, name=Emp4, age=18] Employee [empId=121, name=Emp2, age=30] Sorted by Age Employee [empId=131, name=Emp4, age=18] Employee [empId=111, name=Emp1, age=20] Employee [empId=121, name=Emp2, age=30] Sorted by Name Employee [empId=111, name=Emp1, age=20] Employee [empId=121, name=Emp2, age=30] Employee [empId=131, name=Emp4, age=18]
Arrays.sort() vs Collections.sort()
Arrays.sort is used for arrays which are of primitive data type too. But Collections.sort() works for objects Collections like ArrayList, LinkedList, etc.
Conclusion
In this article we have learned about various ways of sorting array in java. Thanks for reading the article.
Also read-
Java Collection to Array
Java ArrayList vs LinkedList