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:

  1. The length of i's initializer is incorrect (i has five elements, yet the initializer has six).
  2. Hard-coding the 5 into the qsort call is asking for trouble later on.
  3. The name "i" is most commonly used for loop counters and the like.
  4. Calling the comparison function sort is confusing.
  5. Your comparison function is wrong. Consider how it would compare the numbers 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.

Share:
10,636
tom91136
Author by

tom91136

Updated on June 09, 2022

Comments

  • tom91136
    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 1 not sorting the array.....

  • tom91136
    tom91136 over 12 years
    opps , typo, i updated the question, but now, it's not returning sorted array:(
  • NPE
    NPE over 12 years
    @Tom91136: Your sort function is wrong. See the updated answer.
  • tom91136
    tom91136 over 12 years
    thanks! i was so stupid, that sort function was originally used somewhere in my code to sort int arrays...
  • Keith Thompson
    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 to int values won't necessarily fit in an int; for example, INT_MAX - INT_MIN will overflow. A trick I've seen is return (xx > yy) - (xx < yy);.