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 int
s.
What is an optimal alternative given that sorting integers is a very common thing to do?