I am attempting to modify some QuickSort code to have a random number as the pivot.
However, while testing program it doesn’t sort correctly. I’m unsure why this is doing this.
int random (int num) {
int random = rand() % (num - 1);
return random;
}
int* partition (int* first, int* last);
void quickSort(int* first, int* last) {
if (last - first <= 1) return;
int* pivot = partition(first, last);
quickSort(first, pivot);
quickSort(pivot + 1, last);
}
int* partition (int* first, int* last) {
//--int pivot = *(last - 1);
int* pos = (first + random(last - first));
int pivot = *pos;
int* i = first;
int* j = last - 1;
for (;;) {
while (*i < pivot && i < last) i++;
while (*j >= pivot && j > first) j--;
if (i >= j) break;
swap (*i, *j);
}
swap (*pos, *i);
return i;
}
Your first implementation worked but had degenerate behavior with specific datasets. The pivot in your original working code was
*(last - 1)so the simplest fix would be to swap a random element with*(last - 1). The rest of your original partition code would work unchanged.