I don\'t know what I\'m doing wrong but the following code does not sort the array properly.
#include
#include
int compare(
In general case you can't use subtraction to compare integers. Or, more precisely, you can, but only in situations when you are sure that the subtraction will not overflow. In your case subtraction overflows, producing totally meaningless results (not even mentioning that when signed integer subtraction overflows the behavior is undefined).
The common idiom for generating tri-state C-style comparisons between values a
and b
is the (a > b) - (a < b)
expression. It works for data of virtually any comparable types. In your case the comparison function might look as follows
int compare(const void* a, const void* b)
{
int va = *(const int*) a;
int vb = *(const int*) b;
return (va > vb) - (va < vb);
}