我使用C中的qsort
函数对整数的3
列进行排序。它对我的2D数组进行了精细排序,除了最后一项。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#define ARRAYSIZE 10
int array[ARRAYSIZE][3];
static int x_then_z(const void *a, const void *b) {
const int *arr1 = (const int*)a;
const int *arr2 = (const int*)b;
int diff1 = arr1[0] - arr2[0]; //x
if(diff1) return diff1;
return arr1[2] - arr2[2]; //z
}
static int z_then_x(const void *a, const void *b) {
const int *arr1 = (const int*)a;
const int *arr2 = (const int*)b;
int diff1 = arr1[2] - arr2[2]; //z
if(diff1) return diff1;
return arr1[0] - arr2[0]; //x
}
void print_array() {
for(int i = 0; i < ARRAYSIZE; i++){
printf("%d, %d, %dn", array[i][0], array[i][1], array[i][2]);
}
}
int main(int argc, char *argv[]){
fill_array();
//print_array();
//printf("n");
qsort(array, ARRAYSIZE, 3*sizeof(int), x_then_z);
fprintf(stderr, "Sorted by x then zn");
print_array();
printf("n");
qsort(array, ARRAYSIZE, 3*sizeof(int), z_then_x);
fprintf(stderr, "Sorted by z then xn");
print_array();
return EXIT_SUCCESS;
}
我已将列命名为x, y and z
(以免在具有a and b
的比较函数中混淆自己(。fill_array
函数用以下计算输入填充数组:
31, 56, 8
39, 71, 9
65, 76, 10
64, 129, 12
44, 191, 14
105, 199, 15
169, 319, 19
44, 321, 18
319, 364, 22
295, 551, 25
然而,输出是这样的:
Sorted by x then z
31, 56, 8
39, 71, 9
44, 191, 14
44, 321, 18
64, 129, 12
65, 76, 10
105, 199, 15
169, 319, 19
319, 364, 22
**295, 551, 25**
Sorted by z then x
31, 56, 8
39, 71, 9
65, 76, 10
64, 129, 12
44, 191, 14
105, 199, 15
44, 321, 18
169, 319, 19
319, 364, 22
295, 551, 25
您可以看到数组的最后一个值没有排序。如果将ARRAYSIZE
更改为较大的数字,则不会对数组中的最后一个值进行排序。我哪里错了?
fill_array
函数出现了一个off-by-1错误。填充阵列时,它从1开始,而不是0