Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort arrays of double in C

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.....

like image 912
tom91136 Avatar asked Dec 09 '11 16:12

tom91136


People also ask

What is double sort in C?

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.

How do you sort a double array in C#?

Sort(ox_test); and then, just to see if the array it's sorted : for (int y = 1; y <= ox_test. Length; y++) MessageBox.

What is double sort?

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.


1 Answers

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.

like image 163
NPE Avatar answered Oct 21 '22 16:10

NPE