Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using qsort to sort an array of long long int not working for large nos

Tags:

c

qsort

I am using this compare function to sort an array consisting of long long int nos.

int compare(const void * p1,const void * p2)
{
    return (* (long long int * )a-*(long long int * )b);
}
qsort(array,no of elements,sizeof(long long int),compare)

this works fine for small nos but when the array contains nos of the oreder of 10^10 it gives wrong results?

what is the mistake i am making?

like image 952
SHB Avatar asked Jul 14 '13 10:07

SHB


1 Answers

explicitly return -1,1 or 0. This is the following code :

int cmpfunc (const void * a, const void * b)
{
    if( *(long long int*)a - *(long long int*)b < 0 )
        return -1;
    if( *(long long int*)a - *(long long int*)b > 0 )
        return 1;
    return 0;
}
like image 112
Lavish Kothari Avatar answered Sep 27 '22 22:09

Lavish Kothari