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

3

13

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?

Behemoth answered 14/7, 2013 at 10:19 Comment(0)
N
17

The result of compare function must be int. The subtraction of two long long can easily overflow the int type (and it does in your case).

Try comparing the two values explicitly and returning -1, 0 or 1.

Nootka answered 14/7, 2013 at 10:23 Comment(0)
N
7

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;
}
Nugget answered 17/10, 2014 at 15:10 Comment(0)
M
-2
int compare (const void * a, const void * b)
{
  return ( *(int*)a - *(int*)b );
}

qsort (values, 6, sizeof(int), compare);

http://www.cplusplus.com/reference/cstdlib/qsort/

Music answered 4/3, 2014 at 0:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.