Currently trying to figure out what the issue is with this sort. Built directly from the in-place Quicksort pseudocode from Wikipedia, which I am going to assume is reliable. I am attempting to sort an array of structs by a null-terminated 3-character “code” field.
The sort mostly works, but there are always a few elements out of place. I can only assume this has to do with the pivot somehow, but I have spent a few hours staring at it and have gotten nowhere. Thanks!
void quicksort(Cdir *directory, int left, int right) {
if (left < right) {
int pivotIdx = left;
pivotIdx = partition(directory, left, right, pivotIdx);
quicksort(directory, left, pivotIdx - 1);
quicksort(directory, pivotIdx + 1, right);
}
}
int partition(Cdir *directory, int left, int right, int pivot) {
char *pivotVal = directory[pivot].code;
int curIdx = left;
swap(&directory[pivot], &directory[right]);
int i;
for (i = left; i < right; i++) {
if (strncmp(directory[i].code, pivotVal, 3) < 0) {
swap(&directory[i], &directory[curIdx]);
curIdx++;
}
}
swap(&directory[curIdx], &directory[right]);
return curIdx;
}
void swap(Cdir *s1, Cdir *s2) {
Cdir temp = *s1;
*s1 = *s2;
*s2 = temp;
}
I finally figured it out. When I replaced “pivotVal” in my string comparison with a direct reference to the pivot value (directory[right]), the sort works fine. Still trying to decide why that is, but it is fixed!