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

前端 未结 3 801
温柔的废话
温柔的废话 2021-01-14 08:08

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

        
相关标签:
3条回答
  • 2021-01-14 08:50

    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.

    0 讨论(0)
  • 2021-01-14 09:01

    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;
    }
    
    0 讨论(0)
  • 2021-01-14 09:13

    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; */
     }
    
    0 讨论(0)
提交回复
热议问题