gpt4 book ai didi

c - 试图对结构中的数据进行排序,它排序正确但最后一行是错误的

转载 作者:太空宇宙 更新时间:2023-11-04 08:35:26 25 4
gpt4 key购买 nike

 void sort(loc_sos_t a[], int array_size)
{
int i, j;
double index;
loc_sos_t index_block;
for (i = 1; i < array_size; i++){

index = a[i].sos;
index_block= a[i];
for (j = i; j > 0 && a[j-1].sos > index; j--){
a[j].sos = a[j-1].sos;
}

a[j].sos = index;
a[j]= index_block;
}
}

所以这个片段应该以一个结构和整数作为它的参数。该结构是一个数组。在每个索引处,该结构包含 x、y 坐标和瓦特值。该代码片段按升序对瓦特值进行排序,并将其相应的 x,y 坐标带到新位置。

input
30.0 meters east, 70.0 meters north, power 0.0045 watts
53.0 meters east, 63.0 meters north, power 0.0006 watts
36.5 meters east, 27.0 meters north, power 0.0005 watts
70.0 meters east, 25.0 meters north, power 0.0015 watts
20.0 meters east, 50.0 meters north, power 0.0008 watts

output
36.5 meters east, 27.0 meters north, power 0.0005 watts
53.0 meters east, 63.0 meters north, power 0.0006 watts
20.0 meters east, 50.0 meters north, power 0.0008 watts
70.0 meters east, 25.0 meters north, power 0.0015 watts
30.0 meters east, 70.0 meters north, power 0.0045 watts

wrong output generated by wrong code
36.5 meters east, 27.0 meters north, power 0.0005 watts
53.0 meters east, 63.0 meters north, power 0.0006 watts
20.0 meters east, 50.0 meters north, power 0.0008 watts
70.0 meters east, 25.0 meters north, power 0.0015 watts
20.0 meters east, 50.0 meters north, power 0.0045 watts

我输出的最后一行是错误的。请帮忙。我不知道为什么只有一行是错误的。

最佳答案

这是插入排序的代码,对数组值的副本进行了最小的修复(逻辑是正确的,你只是弄乱了数组元素的副本):

void sort(loc_sos_t a[], int array_size) {
int i, j;
double index;
loc_sos_t index_block;
for (i = 1; i < array_size; i++) {
index = a[i].sos;
index_block = a[i];
for (j = i; j > 0 && a[j - 1].sos > index; j--) {
a[j] = a[j - 1];
}
a[j] = index_block;
}
}

无论如何,您可能希望使用标准库中更高效的qsort:

int cmplocsos(const void *p1, const void *p2) {
double s1 = ((loc_sos_t*)p1)->sos;
double s2 = ((loc_sos_t*)p2)->sos;
return (s1 > s2) - (s1 < s2);
}

qsort(&arr[0], array_size, sizeof(loc_sos_t), cmplocsos);

关于c - 试图对结构中的数据进行排序,它排序正确但最后一行是错误的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26442209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com