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.....
This function performs the quicksort sorting algorithm. // qsort(array pointer, number of elements, size of one element, compare function); qsort(grade, n, sizeof(double), compare); In order to compare the elements you also need a compare function.
Sort(ox_test); and then, just to see if the array it's sorted : for (int y = 1; y <= ox_test. Length; y++) MessageBox.
Double Sorting, the idea of processing two chosen elements simultaneously, applies to both Insertion Sort and Selection Sort, with speedups of 33% and 25%, hence are good enough to justify coding, but not good enough to be in Web collections.
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:
i
's initializer is incorrect (i
has five elements, yet the initializer has six).qsort
call is asking for trouble later on.i
" is most commonly used for loop counters and the like.sort
is confusing.1.1
and 1.2
. Also think about what would happen if the difference between the two values doesn't fit in an int
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With