C:qsort似乎不适用于unsigned long

时间:2016-04-17 20:33:47

标签: c unsigned qsort

有谁能告诉我以下示例有什么问题?我从here获取了它,并将int替换为unsigned long。我还更改了cmpfunc以正确处理unsigned long

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

unsigned long values[] = { 88, 56, 100, 2, 25 };

int cmpfunc (const void * a, const void * b)
{
  if(*(unsigned long*)a - *(unsigned long*)b < 0){
    return -1;
  }

  if(*(unsigned long*)a - *(unsigned long*)b > 0){
    return 1;
  }

  if(*(unsigned long*)a - *(unsigned long*)b == 0){
    return 0;
  }
}

int main()
{
   int n;

   printf("Before sorting the list is: \n");

   for( n = 0 ; n < 5; n++ ) 
   {
      printf("%lu ", values[n]);
   }

   qsort(values, 5, sizeof(unsigned long), cmpfunc);

   printf("\nAfter sorting the list is: \n");

   for( n = 0 ; n < 5; n++ ) 
   {   
      printf("%lu ", values[n]);
   }

   return(0);
}

这是我得到的输出:

Before sorting the list is: 
88 56 100 2 25 
After sorting the list is: 
25 2 100 56 88 

1 个答案:

答案 0 :(得分:8)

您的比较功能不正确。减去无符号值可以包含给出不正确结果的值。

该功能只应比较值:

int compare( const void* a , const void* b )
{
    const unsigned long ai = *( const unsigned long* )a;
    const unsigned long bi = *( const unsigned long* )b;

    if( ai < bi )
    {
        return -1;
    }
    else if( ai > bi )
    {
        return 1;
    }
    else
    {
        return 0;
    }
}