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
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.