Sort double arrays in C

if i have an array

double i[5] = {1.023, 1.22, 1.56, 2, 5, 3.331}; 

how to sort the values ​​so that they look like this:

 double i[5] = {1.023, 1.22, 1.56, 2, 3.331, 5}; 

I tried qsort () with no luck, having tried a few 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 .....

+6
source share
1 answer

The first qsort argument is a pointer to the beginning of the array to be sorted. Instead

 qsort(i[5], 5, sizeof(double), sort); 

he must read

 qsort(i, 5, sizeof(double), sort); 

Some additional observations:

  • The length of the initializer i is incorrect ( i has five elements, but the initializer has six).
  • Hard coding 5 into the qsort call causes problems later.
  • The name " i " is most often used for cycle counters, etc.
  • The call to the sort comparison function is confusing.
  • The comparison function is incorrect. See how it will compare numbers 1.1 and 1.2 . Also think about what happens if the difference between the two values ​​does not match int .

I would rewrite your entire example like this:

 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 comparison function above still does not handle NaN correctly; I leave this as an exercise so that the reader can fix it.

+13
source

Source: https://habr.com/ru/post/903463/


All Articles