Sorting: Comparator
Comparators are used to compare two objects. In this challenge, you’ll create a comparator and use it to sort an array. The Player class is provided in the editor below. It has two fields:
- name a string.
- score: an integer.
Given an array of Player objects, write a comparator that sorts them in order of decreasing score. If or more players have the same score, sort those players alphabetically ascending by name. To do this, you must create a Checker class that implements the Comparator interface, then write an int compare(Player a, Player b) method implementing the Comparator.compare(T o1, T o2) method. In short, when sorting in ascending order, a comparator function returns -1 if a<b , 0 if a=b , and 1 if a>b .
Function Description
Declare a Checker class that implements the comparator method as described. It should sort first descending by score, then ascending by name. The code stub reads the input, creates a list of Player objects, uses your method to sort the data, and prints it out properly.
Sample Input
5
amy 100
david 100
heraldo 50
aakansha 75
aleksa 150
Sample Output
aleksa 150
amy 100
david 100
aakansha 75
heraldo 50
Solution:
Explanation:
As you can see, the players are first sorted by decreasing score and then sorted alphabetically by name.
__repr__() function returns the object representation. It could be any valid Python expression such as tuple, dictionary, string, etc.
Given : In short, when sorting in ascending order, a comparator function returns -1 if a<b , 0 if a=b , and 1 if a>b .
From the sample output and question statement, it's clear that we need to sort the name in ascending order and score in descending order. Use the return statement accordingly.
I would strongly urge you not to use nested if block statements in your solutions unless it's needed and there is no workaround. You can often place separate IF blocks in a particular order to get your job done as I have done in my solution.
Hope it helps :)
Follow me on :