Cracking the Coding Interview: Sorting – Comparator

Here’s my solution to the challenge: https://www.hackerrank.com/challenges/ctci-comparator-sorting

struct Player {
    string name;
    int score;
};

bool compare(Player& p1, Player& p2) {
    if(p1.score != p2.score) {
        return (p1.score > p2.score);
    }
    else {
        return (p1.name < p2.name);
    }
}

vector comparator(vector players) {
    sort(players.begin(), players.end(), compare);
    return players;
}

int main() {
    
    int n;
    cin >> n;
    vector players;
    string name;
    int score;
    for(int i = 0; i > name >> score;
        Player p1;
        p1.name = name, p1.score = score;
        players.push_back(p1);
    }
    
    vector answer = comparator(players);
    for(int i = 0; i < answer.size(); i++) {
        cout << answer[i].name << " " << answer[i].score << endl;
    }
    return 0;
}

All my solutions to HackerRank challenges can be found here: https://github.com/sdulaney/hackerrank

Leave a Comment