0

c library function qsort takes a comparison function to compare integers. Google search suggests the following

int compare (const void *a, const void *b)
{
    const int *ia = (const int *)a; // casting pointer types 
    const int *ib = (const int *)b;
    return *ia  - *ib; 
}

This has the problem of signed integer overflow(or underflow) which is undefined in c. The straightforward solution is very verbose and may not be the best.

int compare (const void *a, const void *b) {
    const int *ia = (const int *)a; // casting pointer types 
    const int *ib = (const int *)b;
    if(*ia > *ib) {
        return 1;
    } else if (*ia == *ib) {
        return 0;
    }
    return -1;
}

Other option is to use wider length signed integers like long long int, but the problem still remains when we have to sort long long ints.

What is an optimal alternative given that sorting integers is a very common thing to do?

balki
  • 26,394
  • 30
  • 105
  • 151
  • 2
    What is the problem with the solution you have? You might have better luck at [codereview](http://codereview.stackexchange.com) – Ryan Haining Apr 14 '18 at 18:25
  • 2
    the answer of chux is probably the best you can do. – Stargateur Apr 14 '18 at 18:28
  • 1
    There are many similar questions. Your second comparator is more correct than the first, precisely because of possible overflow. You could use `int ia = *(const int *)a; int ib = *(const int *)b;` then compare `ia` and `ib` rather than using pointers throughout, but the compiler probably optimizes it for you anyway. – Jonathan Leffler Apr 14 '18 at 18:30
  • No need to cast those `void`-pointers in C. – alk Apr 15 '18 at 08:59

0 Answers0