Using Quick Sort in C to sort in reverse direction (descending)?

五迷三道 提交于 2020-07-15 08:23:21

问题


To sort I call 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;
    }
}

First, This doesn't really work, when I sort an array (9,8,7,6,5,4,3,2,1,1), I get (4,8,7,6,5,9,3,2,1) - NOT really sorted.

Second, How would I sort in the other direction? Is there a special flag for qsort I need to pass?


回答1:


Change your compare function so that it is ordering the way you like.

And the compare function takes pointers to compared data (not the data itself). Eg.

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; */
 }



回答2:


You need to compare the values, not their addresses. Try

int comp(const int * a, const int * b)
{
 return *a - *b;
}

To reverse the ordering, use

int comp(const int * a, const int * b)
{
 return *b - *a;
}



回答3:


Your comparator is broken. You are comparing the pointer values rather than the values being pointed to. Add the * dereference operator to the a and b comparisons and it should work.



来源:https://stackoverflow.com/questions/8115624/using-quick-sort-in-c-to-sort-in-reverse-direction-descending

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!