I have been trying to implement sort_pairs function using selection sort algorithm. After testing for every case, the sort_pairs is returning right answer but check50 is marking it as wrong.

for (int i = 0; i < pair_count - 1; i++)
        winner_index = pairs[i].winner;
        loser_index = pairs[i].loser;
        diff = preferences[winner_index][loser_index];
        int max_index = i;
        for (int j = i+1; j < pair_count; j++)
            winner_index1 = pairs[j].winner;
            loser_index1 = pairs[j].loser;
            int diff2 = preferences[winner_index1][loser_index1];
            if (diff2 > diff)
                max_index = j;

        if (i != max_index)
            pairs[i].winner = winner_index1;
            pairs[i].loser = loser_index1;

            pairs[max_index].winner = winner_index;
            pairs[max_index].loser = loser_index;

Here's the code for reference.

Before Sorting 
c a 6
b c 5
a b 7
After Sorting 
a b 7
c a 6
b c 5

This is what I am getting as an output where a,b,c are candidates and the numbers are preferences.


Check with strengths 1, 3, 2, in that order, with the highest value not being last.

When you update max_index, you should also update diff. Otherwise, a later pair might be chosen that's stronger than the initial pair, but not the overall strongest.

Alternatively, directly use pairs[max_index] for the comparison.

Your swap action also relies on winner_index1 and loser_index1 to represent the pair to swap with, but they are the pair checked last, which is not necessarily same as pairs[max_index] in either version.

You could use a temporary variable for swapping, like

pair temp = pairs[i];
pairs[i] = pair[max_index];
pairs[max_index] = temp;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .