O
O
Old Odessa2016-06-25 16:26:22
Algorithms
Old Odessa, 2016-06-25 16:26:22

How to sort double array using qsort?

qsort(array, size, sizeof(double), compare);
int compare (const void *a, const void *b){
return (*(double*)a - *(double*)b);
}
An array of 10,000, tell me why it doesn't sort the fractional part normally, sorts the integer part in general but with a lot of errors?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
rhaport, 2016-06-25
@rhaport

The problem is that you cast the difference of two doubles to int, if it is small, then the comparator will return 0!

int cmp(const void *a, const void *b) 
{
    const double *ad, *bd;
    
    ad = (const double*)a;
    bd = (const double*)b;
   
    if (*ad < *bd) 
    {   
        return -1;   
    }   
    else if (*ad > *bd)
    {   
        return 1;
    }   
    else
    {   
        return 0;
    }   
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question