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;
}
}
因此,该代码段应该以struct和integer作为其参数。该结构是一个数组。在每个索引处,该结构均包含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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句