0

So I have this array of structs that is holding data about competitors within a race. This is how the struct is set up:

struct competitor {
        int compID;
        char name[30];
        int swimSecs;
        int cyclSecs;
        int runSecs;
        int totalSecs;
    };

I'm using this sorting array to arrange the competitors in order from smallest to biggest. compNum is the number of competitors

void sort(struct competitor** a) {

    int n = compNum;


    struct competitor temp;
    int i, j;

    for (i = 1; i < n; i++)
        for (j = 0; j < n - i; j++) {



            if (a[j]->totalSecs > a[j + 1]->totalSecs) {


                temp = *a[j];

                a[j] = a[j + 1];

                *a[j + 1] = temp;

            }
        }


    return;
}

But it seems that when using temp and swapping structs around, it seems to duplicate some of the structs that have been inputted by the user and overwrite existing struct data. Can anyone see why this may be occurring, and how would you fix it? Thank you in advance

Unfitacorn
  • 186
  • 2
  • 12

1 Answers1

2

You should either swap structures, which makes the code be:

temp = *a[j];
*a[j] = *a[j + 1];   // copy the structure
*a[j + 1] = temp;

Or, and more preferably for efficiency, just swap the pointers:

struct competitor *temp;
...

temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;

The code currently is doing a little of both, which will not work.

lurker
  • 56,987
  • 9
  • 69
  • 103
  • Thank you for responding, I went with @lurker solution which is the same as the first solution you produced. Thank you again. – Unfitacorn Nov 09 '15 at 20:23
  • @Unfitacorn I am Lurker who posted this answer - I removed my comment to make it an answer. :) If you found my answer acceptable, if you wouldn't mind checking the "accept" I'd be much obliged. :) – lurker Nov 09 '15 at 20:31