sort arrays of double in C
10,636
The first argument to qsort
is the pointer to the start of the array to be sorted. Instead of
qsort(i[5], 5, sizeof(double), sort);
it should read
qsort(i, 5, sizeof(double), sort);
Some further observations:
- The length of
i
's initializer is incorrect (i
has five elements, yet the initializer has six). - Hard-coding the 5 into the
qsort
call is asking for trouble later on. - The name "
i
" is most commonly used for loop counters and the like. - Calling the comparison function
sort
is confusing. - Your comparison function is wrong. Consider how it would compare the numbers
1.1
and1.2
. Also think about what would happen if the difference between the two values doesn't fit in anint
.
I would rewrite your entire example like so:
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);
}
Note that the above comparison function still doesn't correctly handle NaNs; I leave it as an exercise for the reader to fix that.
Author by
tom91136
Updated on June 09, 2022Comments
-
tom91136 almost 2 years
if I have an array
double i[5] = {1.023, 1.22, 1.56, 2, 5, 3.331};
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};
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); }
with =>
error: incompatible type for argument 1not sorting the array..... -
tom91136 over 12 yearsopps , typo, i updated the question, but now, it's not returning sorted array:(
-
NPE over 12 years@Tom91136: Your
sort
function is wrong. See the updated answer. -
tom91136 over 12 yearsthanks! i was so stupid, that sort function was originally used somewhere in my code to sort int arrays...
-
Keith Thompson over 12 years@Tom91136: Even for int arrays, that comparison function (please don't call it
sort
) won't always work. The difference between toint
values won't necessarily fit in anint
; for example,INT_MAX - INT_MIN
will overflow. A trick I've seen isreturn (xx > yy) - (xx < yy);
.