【问题标题】:using qsort to sort an array of long long int not working for large nos使用 qsort 对 long long int 数组进行排序不适用于大型 nos
【发布时间】:2013-07-12 09:19:13
【问题描述】:

我正在使用这个比较函数对一个由 long long int nos 组成的数组进行排序。

int compare(const void * p1,const void * p2)
{
    return (* (long long int * )a-*(long long int * )b);
}
qsort(array,no of elements,sizeof(long long int),compare)

这适用于小编号,但是当数组包含 10^10 的序数时,它会给出错误的结果?

我犯了什么错误?

【问题讨论】:

    标签: c qsort


    【解决方案1】:

    compare 函数的结果必须是int。两个long long 的减法很容易溢出int 类型(在您的情况下确实如此)。

    尝试显式比较这两个值并返回 -1、0 或 1。

    【讨论】:

      【解决方案2】:

      显式返回 -1,1 或 0。这是以下代码:

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

      【讨论】:

        【解决方案3】:
        int compare (const void * a, const void * b)
        {
          return ( *(int*)a - *(int*)b );
        }
        
        qsort (values, 6, sizeof(int), compare);
        

        http://www.cplusplus.com/reference/cstdlib/qsort/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-01-13
          • 1970-01-01
          • 1970-01-01
          • 2019-05-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多