Open In App

Sort an Array in Java using Comparator

Last Updated : 24 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A Comparator is an object that can be used to compare two objects and determine their order. We can use a Comparator to sort a list of objects in any order we can choose, not just in ascending order.

Examples:

Array(Ascending Order):
Input: arr = (4, 2, 5, 1, 3)
Output: [1, 2, 3, 4, 5]

Array(Descending Order):
Input: arr = (4, 2, 5, 1, 3)
Output: [5, 4, 3, 2, 1]

Strings(Ascending Order):
Input: str = ("Jan", "Tommy", "Jo", "Adam")
Output: [Jo, Jan, Adam, Tommy]

Strings(Ascending Order):
Input: str = ("Jan", "Tommy", "Jo", "Adam")
Output: [Tommy, Adam, Jan, Jo]

Algorithm

  1. Implement the Comparator interface and override the compare method.
  2. In the compare method, compare the two objects and return a negative integer if the first object is less than the second, a positive integer if the first object is greater than the second, or 0 if they are equal.
  3. To sort an array using the comparator first we convert the array into the list, call the sort method on the list and pass an instance of the comparator as an argument.

Below are the implementations of the above algorithm for strings and integers (Ascending and Descending both).

For Array (Ascending Order)


Output
[3, 5, 6, 7, 10]

For Array (Descending Order)


Output
[20, 15, 10, 5, 3]

For Strings (Ascending Order)


Output
[Jo, Jan, Adam, Tommy]

For Strings (Descending Order)


Output
[GeeksforGeeks, from, am, I]

Sorting Using Custom Comparator

We can sort an array using a custom comparator by using the Arrays.sort() method along with a Comparator.


Output
Sorted by age: [Shivansh (25), Happy (30), Divyansh (35)]
Sorted by name: [Divyansh (35), Happy (30), Shivansh (25)]

Explanation: The comparator that we provided has a time complexity of O(n log(n)), where n is the number of elements in the list. This is because the sort method uses a comparison-based algorithm (such as merge sort or quick sort) to sort the list, and the time complexity of these algorithms is O(n * log(n)). The space complexity of the comparator is O(1) since it does not allocate any additional memory beyond the comparator object itself.


Next Article

Similar Reads