I am trying to implement a custom quicksort and a custom comparator because i need to sort a struct by two elements (if the first are equal, sort by the second).
I used the following code, which was originally posted at the first answer of: Sorting an array using multiple sort criteria (QuickSort)
typedef struct player {
int total;
char name[16];
} player;
void swap(player *p1,player *p2) {
player tmp = *p2;
*p2 = *p1;
*p1 = tmp;
}
int comp(const player *p1,const player *p2) {
if (p1->total < p2->total) return 1;
if (p1->total > p2->total) return -1;
return strcmp(p1->name, p2->name);
}
static void quickSort(player *arr, int left, int right) {
int m = (left+right)/2;
int l = left, r = right;
while (l <= r) {
while (comp(arr+l, arr+m) < 0) l++;
while (comp(arr+r, arr+m) > 0) r--;
if (l <= r) {
swap(arr+l, arr+r);
l++; r--;
}
}
if (r > left) quickSort(arr, left, r);
if (l < right) quickSort(arr, l, right);
}
I cant get this to work. It will succesfully sort by total but fails to sort by name when the two totals are equal.
Yes, Ive tried using this comparator with the standard qsort function and it worked just fine. But using it will be my last alternative.
Any help is appreciated.
Edit:
I am guessing the pivot is the problem. When I add 1 to it the 'name' ordering works fine but a few 'total' elements gets out of order.