c - qsort compare function behaviour -
everyone. trying change compare function , okay if write sth 0 -5.5 in infile output recive (after qsort) -5.5 greater 0, , that's not true. check code , tell me should chage?
int compare(const void *str1, const void *str2) { char *number1, *number2; int len1=0, len2=0, dot1=0, dot2=0, value=0; int minus1=0, minus2=0; number1 = *(char**)str1; number2 = *(char**)str2; while(*number1=='0') number1++; while(*number2=='0') number2++; while(*number1 || *number2){ if(value==0) {value= *number1-*number2;} if(*number1){ if(*number1=='-') number1++; if(*number1=='-') minus1=1; if(*number1!='.'){ number1++; if(dot1==1) len1++;} if(*number1=='.'){ number1++; dot1=0;} } if(*number2){ if(*number2=='-') number2++; if(*number2=='-') minus2=1; if(*number2!='.'){ number2++; if(dot2==1) len2++;} if(*number2=='.'){ number2++; dot2=0;} } } if(minus1>0 && minus2==0){return -1;} if(minus1==0 && minus2>0){return 1;} if(minus1>0 && minus2>0){ if(len1>len2) return -1; if(len2>len1) return 1; return (-value);} if(len1>len2) return 1; if(len2>len1) return -1; return value; }
i suggest use double
array treated qsort
, bsearch
.
but if insist use char *
:
int compare( const void * l, const void * r ) { char * lerr = null; char * rerr = null; double left = strtod((const char *)l, &lerr ); double right = strtod((const char *)l, &rerr ); return (*lerr||*rerr) ? (int)(l-r) : (int)(left-right); }
Comments
Post a Comment