why is the sort function not sorting a struct?

Viewed 65

I have the pair struct below which contains two variables:

typedef struct
{
    int winner;
    int loser;
}
pair;

And I am trying to sort them according to the array pair_strength which is in the same length. However, while the sorting function seems fine, the ordering of the pair struct is not changing at all. Below is the sort function:

int pair_strength[] = {1, 5, 2, 4, 3};
void sort_pairs(void)
{
    // bubble sort
    for (int i = 0; i < pair_count-1; i++)
    {
        for (int j = 0; j < pair_count-i-1; j++)
        {
            if (pair_strength[j] < pair_strength[j+1])
            {
                int temp_w = pairs[j].winner;
                int temp_l = pairs[j].loser;
                pairs[j].winner = pairs[j+1].winner;
                pairs[j].loser = pairs[j+1].loser;
                pairs[j+1].winner = temp_w;
                pairs[j+1].loser = temp_l;
            }
        }
    }

}

Therefore, given that 5 is the second element in pair_strength and is the biggest number, I want to move the second elements in both variables ( winner and loser) in pair struct to the first and so on

1 Answers

Thank you all for your help. Below is updated function:

void sort_pairs(void)
{
    // bubble sort
    for (int i = 0; i < pair_count-1; i++)
    {
        for (int j = 0; j < pair_count-i-1; j++)
        {
            if (pair_strength[j] < pair_strength[j+1])
            {
                pair t = pairs[j];
                pairs[j] = pairs[j+1];
                pairs[j+1] = t;
                int t2 = pair_strength[j];
                pair_strength[j] = pair_strength[j+1];
                pair_strength[j+1] = t2;
            }
        }
    }

}
Related