代码之家  ›  专栏  ›  技术社区  ›  kurdtpage Yunus Malek

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

  •  1
  • kurdtpage Yunus Malek  · 技术社区  · 8 年前

    我正在使用 qsort 函数在C中排序 3 整数列。它对我的二维数组排序很好, 最后一项除外


    这是我的代码:

    #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 对于较大的数字,数组中的最后一个值不排序。我哪里出错了?

    1 回复  |  直到 8 年前
        1
  •  0
  •   kurdtpage Yunus Malek    8 年前

    这个 fill_array 函数出现“关闭1”错误。填充数组时,它从1开始,而不是0