繁体   English   中英

C qsort不对多维数组中的最后一项进行排序

[英]C qsort not sorting last item in multidimensional array

我在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, %d\n", 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 z\n");
    print_array();

    printf("\n");

    qsort(array, ARRAYSIZE, 3*sizeof(int), z_then_x);
    fprintf(stderr, "Sorted by z then x\n");
    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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM