Sorting: comparator Solution

carlosbf
carlosbf
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;
}}
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade