Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question