C qsort not working correctly

后端 未结 4 2154
北荒
北荒 2020-12-16 16:42

I don\'t know what I\'m doing wrong but the following code does not sort the array properly.

#include 
#include 

int compare(         


        
4条回答
  •  轮回少年
    2020-12-16 17:12

    In general case you can't use subtraction to compare integers. Or, more precisely, you can, but only in situations when you are sure that the subtraction will not overflow. In your case subtraction overflows, producing totally meaningless results (not even mentioning that when signed integer subtraction overflows the behavior is undefined).

    The common idiom for generating tri-state C-style comparisons between values a and b is the (a > b) - (a < b) expression. It works for data of virtually any comparable types. In your case the comparison function might look as follows

    int compare(const void* a, const void* b)
    {
      int va = *(const int*) a;
      int vb = *(const int*) b;
      return (va > vb) - (va < vb);
    }
    

提交回复
热议问题