要排序,我调用 qsort(myArray,100,sizeof(int), comp)
int comp(const int * a, const int * b)
if(a==b)
{
return 0;
}
else
{
if(a<b)
{
return -1;
}
else
{
return 1;
}
}
第一的,
这实际上不起作用,当我对数组
(9,8,7,6,5,4,3,2,1,1),
进行排序时,我得到 (4,8,7,6,5,9,3,2,1)
- 没有真正排序。第二,
我将如何在另一个方向排序?我需要通过 qsort 的特殊标志吗?
最佳答案
更改您的比较功能,使其按您喜欢的方式排序。
并且比较函数采用指向比较数据(而不是数据本身)的指针。例如。
int compare (const void* p1, const void* p2)
{
int i1 = *(int*) p1;
int i2 = *(int*) p2;
if (i1 < i2) return -1;
else if (i1 == i2) return 0;
else return 1;
/* or simply: return i1 - i2; */
}
关于c - 在 C 中使用快速排序进行反向排序(降序)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8115624/