Search code examples
cqsort

qsort does not work for double array


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


Solution

  • 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.)