C 对函数中的结构数组进行排序
所以我有一个结构数组,它保存着比赛中竞争对手的数据。以下是结构的设置方式:C 对函数中的结构数组进行排序,c,arrays,struct,temp,C,Arrays,Struct,Temp,所以我有一个结构数组,它保存着比赛中竞争对手的数据。以下是结构的设置方式: struct competitor { int compID; char name[30]; int swimSecs; int cyclSecs; int runSecs; int totalSecs; }; 我用这个排序数组把竞争对手按从最小到最大的顺序排列。compNum是竞争对手的数量 void sort(s
struct competitor {
int compID;
char name[30];
int swimSecs;
int cyclSecs;
int runSecs;
int totalSecs;
};
我用这个排序数组把竞争对手按从最小到最大的顺序排列。compNum是竞争对手的数量
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;
}
void排序(结构**a){
int n=compNum;
结构竞争对手温度;
int i,j;
对于(i=1;itotalSecs>a[j+1]>totalSecs){
温度=*a[j];
a[j]=a[j+1];
*a[j+1]=温度;
}
}
返回;
}
但是,当使用temp和交换结构时,它似乎复制了用户输入的一些结构,并覆盖了现有的结构数据。有人知道为什么会发生这种情况吗?你会怎么解决?提前感谢您应该交换结构,这使得代码是:
temp = *a[j];
*a[j] = *a[j + 1]; // copy the structure
*a[j + 1] = temp;
或者,为了提高效率,最好交换指针:
struct competitor *temp;
...
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
代码目前正在同时执行这两项操作,但都不起作用。为什么不使用编译器附带的
qsort
实现?@owacorder我必须自己实现排序算法。@潜伏者我必须自己实现排序算法。@unftacorn请看我编辑的评论。@owacorder谢谢,这非常有效。感谢您的回复,我选择了@潜伏者解决方案,它与您制作的第一个解决方案相同。再次感谢。@unftacorn我是发布此答案的潜伏者-我删除了我的评论以作为答案。:)如果您认为我的答案可以接受,如果您不介意勾选“接受”,我将不胜感激。:)