sort arrays of double in C

tom*_*136 6 c arrays sorting double

if I have an array

double i[5] = {1.023, 1.22, 1.56, 2, 5, 3.331};
Run Code Online (Sandbox Code Playgroud)

how do i sort the values so that they look like this:

double i[5] = {1.023, 1.22, 1.56, 2, 3.331, 5};
Run Code Online (Sandbox Code Playgroud)

i've tried qsort() with no luck, after trying some examples, i came up with:

qsort(i, 5, sizeof(double), sort);

int sort(const void *x, const void *y)
{
return (*(double*)x - *(double*)y);
}
Run Code Online (Sandbox Code Playgroud)

with => error: incompatible type for argument 1 not sorting the array.....

NPE*_*NPE 13

第一个参数qsort是指向要排序的数组的开头的指针.代替

qsort(i[5], 5, sizeof(double), sort);
Run Code Online (Sandbox Code Playgroud)

它应该读

qsort(i, 5, sizeof(double), sort);
Run Code Online (Sandbox Code Playgroud)

进一步的观察:

  1. i初始化程序的长度不正确(i有五个元素,但初始化程序有六个).
  2. 将5硬编码到qsort呼叫中是为了以后遇到麻烦.
  3. 名称" i"最常用于循环计数器等.
  4. 调用比较功能sort令人困惑.
  5. 你的比较功能是错误的.考虑如何比较数字1.11.2.还要考虑如果两个值之间的差异不适合,会发生什么int.

我会像这样重写你的整个例子:

double arr[] = {1.023, 1.22, 1.56, 2, 5, 3.331};

int cmp(const void *x, const void *y)
{
  double xx = *(double*)x, yy = *(double*)y;
  if (xx < yy) return -1;
  if (xx > yy) return  1;
  return 0;
}

int main() {
  qsort(arr, sizeof(arr)/sizeof(arr[0]), sizeof(arr[0]), cmp);
}
Run Code Online (Sandbox Code Playgroud)

注意,上面的比较函数仍然没有正确处理NaNs; 我把它作为练习让读者解决这个问题.

  • @ Tom91136:即使对于int数组,这个比较函数(*请*不要称之为`sort`)也不会一直有效.`int`值之间的差异不一定适合`int`; 例如,`INT_MAX - INT_MIN`将溢出.我看到的一个技巧是`return(xx> yy) - (xx <yy);`. (2认同)