I came across a qsort comparator function that was incorrectly using "a > b" as the comparison operation. I would expect this code to just somewhat randomly reorder the array, but it was working on my school's instructional servers (Ubuntu 12.04.4 LTS). It didn't work on my own laptop as expected, so I'm not sure what could be causing this bug.
#include <cstdio>
#include <cstdlib>
void print_arr(int* arr, size_t n) {
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int int_compar(const void *x, const void *y)
{
int i_x = *((int*)x);
int i_y = *((int*)y);
return i_x > i_y;
}
int main(int argc, char *argv[])
{
int n = (1<<4);
int in[n];
for(int i = 0; i < n; i++)
in[i] = rand() % 100;
printf("Before: ");
print_arr(in, n);
qsort(in, n, sizeof(int), int_compar);
printf("After: ");
print_arr(in, n);
return 0;
}
My laptop:
$ ./qsort_test
Before: 7 49 73 58 30 72 44 78 23 9 40 65 92 42 87 3
After: 23 7 9 3 58 44 42 40 49 30 65 72 73 78 87 92
Ubuntu:
$ ./qsort_test
Before: 83 86 77 15 93 35 86 92 49 21 62 27 90 59 63 26
After: 15 21 26 27 35 49 59 62 63 77 83 86 86 90 92 93
qsort
implementation that happens to produce the correct result for that particular input set with that particular (broken) comparator. – Oliver Charlesworthqsort()
evidently does the same thing when thefcmp()
return value is< 0
or0
. OP'sqsort()
takes a different path, maybe does the same on> 0
or0
. – chux - Reinstate Monicai_x < i_y
– Weather Vane