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 1
not sorting the array…..
The first argument to
qsortis the pointer to the start of the array to be sorted. Instead ofit should read
Some further observations:
i‘s initializer is incorrect (ihas five elements, yet the initializer has six).qsortcall is asking for trouble later on.i” is most commonly used for loop counters and the like.sortis confusing.1.1and1.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:
Note that the above comparison function still doesn’t correctly handle NaNs; I leave it as an exercise for the reader to fix that.