Hi,
I am trying to qsort an array of floats and for some reason I am not getting the proper results. I am posting my code here. Could any of you take a look and tell me what I am missing.
When I run this, I am getting an array which is ordered differently from the original array. But not properly sorted.Code:#include <stdio.h> #include <stdlib.h> int compare(const void*a, const void*b) { int a1 = ( *(float*) a); int a2 = ( *(float*) b); return a1 -a2; } int main() { float array[] = { 1605748992, 2242276608, 6265311232, 8249718272, 1181892352, 2202173184, 411911232, 6999099904, 11551354880, 5034336768,2997344512,636791104,1221603328,2306947328,7531588096,8709864448,7865203712,1004122048,2171712000,4130571776,4451974656 }; int i,j, lib_no =21; for(i=0; i<lib_no; i++) { printf("%f\n",array[i]); } printf("\n\n\n\n"); qsort(&array[0], lib_no, sizeof(float), compare); for(i=0; i<lib_no; i++) { printf("%f\n",array[i] ); } return 0; }
I think that the problem is something in the the way I am typecasting the void pointers inside the compare function. But not sure what..I was earlier doing it like this..
and that gave me an output with a different order. But again not properly sorted. Does anyone have any suggestions on what I should try? What am I doing wrong?Code:int compare(const void*a, const void*b) { return (int) ( *(float*)a - *(float*)b) ); }
Thanks,
Avinash



LinkBack URL
About LinkBacks


