![]() |
VOOZH | about |
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]
Below are the implementations of the above algorithm for strings and integers (Ascending and Descending both).
[3, 5, 6, 7, 10]
[20, 15, 10, 5, 3]
[Jo, Jan, Adam, Tommy]
[GeeksforGeeks, from, am, I]
We can sort an array using a custom comparator by using the Arrays.sort() method along with a Comparator.
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.