Sorting: comparator Solution
Sep 2, 2018 · 1 min read
This is one of the medium difficulty problems in the sorting section of hackerrank’s interview preparation kit problem set. Link here.
The problem asks you to implement a comparator between 2 instances of the Player data structure. Your comparator function will be called by a sorting implementation. You want to sort in decreasing order of score and if two players have the same score, alphabetically.
Solution
The problem can be solved in 6 lines. The code is very self-explanatory. Additionally I think this problem should be easy instead of medium in difficulty.
Code
class Checker{ public: static int comparator(Player a, Player b){
if(a.score == b.score)
if (a.name == b.name)
return 0;
else
return ( a.name > b.name )? -1:1;
return (a.score<b.score)?-1:1; }}
