2015年10月19日 星期一

qsort in c library

qsort shouldn't use a compare function like
int cmp(const void* a, const void* b){
    return *(int*)a - *(int*)b;
}
it would easily cause a overflow, like 2000000000-(-2000000000), it would  overflow and become a negative number.

instead, we should use a compare function like
int cmp(const void* a, const void* b){
    if(*(int*)a > *(int*)b)return 1;
    else if(*(int*)a < *(int*)b)return -1;
    return 0;
}

沒有留言:

張貼留言