c89 - Problem trying to use the C qsort function -


#include <stdio.h> #include <stdlib.h>  float values[] = { 4, 1, 10, 9, 2, 5, -1, -9, -2,10000,-0.05,-3,-1.1 };  int compare (const void * a, const void * b) {     return ( (int) (*(float*)a - *(float*)b) ); }  int main () {      int i;      qsort (values, 13, sizeof(float), compare);      (i = 0; < 13; i++)     {         printf ("%f ",values[ ]);     }     putchar('\n');      return 0; } 

the result is:

-9.000000 -3.000000 -2.000000 -1.000000 -1.100000 -0.050000 1.000000 2.000000 4.000000 5.000000 9.000000 10.000000 10000.000000

it's wrong because order of -1 , -1.1 changed. believe happening because "compare" function.

how can fix this?

thanks

your comparison function broken. says, example, -1.0 equal (equivalent) -1.1, since (int) ((-1.0) - (-1.1)) zero. in other words, told qsort relative order of -1.0 , -1.1 not matter. why surprised in resultant ordering these values not sorted?

in general, should avoid comparing numerical values subtracting 1 another. doesn't work. floating-point types might produce imprecise results quite few different reasons, 1 of observed yourself. integer types might overflow.

the generic idiom comparing 2 numerical values a , b qsort looks (a > b) - (a < b). remember , use it. in case

int compare (const void * a, const void * b) {   float fa = *(const float*) a;   float fb = *(const float*) b;   return (fa > fb) - (fa < fb); } 

in c code might make perfect sense define macro

#define compare(a, b) (((a) > (b)) - ((a) < (b))) 

and use instead of spelling out comparisons explicitly.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -