C qsort 奇怪的行为

标签 c sorting qsort

我正在尝试执行以下操作:

  1. 为维度为 7 的数组分配内存
  2. 写出前 4 个位置
  3. 对这 4 个位置进行排序。
  4. 写出剩余的 3 个位置
  5. 对整个数组进行排序。

我有数组(1,6,2,3),排序后变成(1,2,3,6)

然后我写下剩余的位置,即(1,2,3,6,1,5,1)

排序后,我应该得到(1,1,1,2,3,5,6),但我却得到了 (6,2,3,1,1,5,1)

这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int comp(const void* a, const void* b);

typedef struct{

    int peso;
 }aresta_;

int main(int argc, const char * argv[]) {

    aresta_* array /*struct array, has field peso of type int*/;
    int dim=7;
    int dim_aux=4;
    int i;

    array = (aresta_*) malloc(dim * sizeof(aresta_));

    array[0].peso=1;
    array[1].peso=6;
    array[2].peso=2;
    array[3].peso=3;


    printf("First sort:\n");
    for(i=0; i<dim_aux; i++)
        printf("%d ",array[i].peso);

    printf("\n");


    qsort(array, dim_aux, sizeof(array[0]), comp);


    for(i=0; i<dim_aux; i++)
        printf("%d ",array[i].peso);

    printf("\n\n");

    array[4].peso=1;
    array[5].peso=5;
    array[6].peso=1;

    printf("Second sort:\n");


    for(i=0; i<dim; i++)
        printf("%d ",array[i].peso);

    printf("\n");

    qsort(array, dim, sizeof(array[0]), comp);

    for(i=0; i<dim; i++)
        printf("%d ",array[i].peso);




    printf("\n");

}

我的补偿功能:

int comp(const void* a, const void* b)
{
    aresta_* a1 = (aresta_*)a;
    aresta_* b1 = (aresta_*)b;
    return a1->peso > b1->peso;
}

输出:

First sort:
1 6 2 3 
1 2 3 6 

Second sort:
1 2 3 6 1 5 1 
6 2 3 1 1 5 1 
Program ended with exit code: 0

我哪里出错了?任何帮助将不胜感激。

最佳答案

OP的函数只返回0和1。@Weather Vane

因为这对 OP 的前 4 个值“有效”,所以是“运气”。

比较函数需要返回 3 个结果中的 1 个:负数、0 或正数。

The function shall return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
C11dr §7.22.5.2 3

int comp(const void* a, const void* b)
{
    const aresta_* a1 = (const aresta_*)a;
    const aresta_* b1 = (const aresta_*)b;
    // return a1->peso > b1->peso;
    return (a1->peso > b1->peso) - (a1->peso < b1->peso);
}

return (a1->peso > b1->peso) - (a1->peso < b1->peso);return a1->peso - b1->peso;有优势。这个答案不会溢出。它对于所有 int 对都是有效且功能正确的。 。各种编译器都能识别这种习​​惯用法并生成紧凑的代码。 int - int可能会溢出,这是未定义的行为,UB。

关于C qsort 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43723947/

相关文章:

python - 为 Python 模块编译 C 代码时出现问题

C unicode 到 ascii

c - Arduino 在大约 9 个循环后停止执行

c++ - 如何在 C++ 中使用堆栈、队列或 BST 对文件中的记录进行排序?

javascript - 使用 Javascript 计算数组中元素的数量

arrays - 排序或非整数数组的复杂性

arrays - 堆内存中的数组排序

c - 异或/或运算符?

c - 帮助解决函数中的段错误

c - C语言中 float 相减