qsort does not work for double array

南笙酒味 提交于 2021-02-20 03:42:39

问题


I try to sort an array of double value using qsort, but it doesn't seems to work. Wonder what has gone wrong here??

#include <stdio.h>
#include <stdlib.h>
static double compare (const void * a, const void * b)
{
  if (*(double*)a > *(double*)b) return 1;
  else if (*(double*)a < *(double*)b) return -1;
  else return 0;  
}

int main() {

    int idx;
    double* sum_least_square_err;

    sum_least_square_err = (double*) malloc (2500*2500*sizeof(double));

    sum_least_square_err[0] = 0.642;    
    sum_least_square_err[1] = 0.236;
    sum_least_square_err[2] = 0.946;
    idx = 3;

    qsort(sum_least_square_err, idx, sizeof(sum_least_square_err), compare);

    int i;
    for (i=0; i<idx; i++){
       fprintf(stderr,"sum_least_square_err[%d] = %.3f\n", i, sum_least_square_err[i]);            
    }
    fprintf(stderr,"MAEE = %.3f\n", sum_least_square_err[idx/2]);

    free(sum_least_square_err);
}

Result:

sum_least_square_err[0] = 0.642

sum_least_square_err[1] = 0.236

sum_least_square_err[2] = 0.946

MAEE = 0.236


回答1:


Change:

static double compare (const void * a, const void * b)

to:

static int compare (const void * a, const void * b)

and change:

qsort(sum_least_square_err, idx, sizeof(sum_least_square_err), compare);

to:

qsort(sum_least_square_err, idx, sizeof(sum_least_square_err[0]), compare);

Note: you should have got an appropriate compiler warning about the first bug - are you compiling with gcc -Wall or equivalent, and if so are you taking notice of compiler warnings ? (If not then please take the hint and let the compiler catch problems such as this for you in future.)




回答2:


I believe your error is at the line:

qsort(sum_least_square_err, idx, sizeof(sum_least_square_err), compare);

The problem is the 3rd parameter should be sizeof(double), that is, the size of an element of the array. You were instead passing the size of a pointer, which can be (and usually is) different from the size of the element.

For more information, see: http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/

Edit: And Paul R is right in his answer: The prototype of your comparison function is wrong. The prototype should be:

int ( * comparator ) ( const void *, const void * )

Last but not least, in your code:

if (*(double*)a > *(double*)b) return 1;
else if (*(double*)a < *(double*)b) return -1;

You are casting away the const. This has not consequence here, but still, this is bad form.



来源:https://stackoverflow.com/questions/11931547/qsort-does-not-work-for-double-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!