Currently, I have a barebones implementation of the quicksort algorithm to sort some randomly generated numbers. The sort is efficient, more so than merge sort. However, for specific number sets (e.g. reversed numbers that need to be sorted the other way around), I need to optimized the pivot.
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* 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 (*(last - 1), *i);
return i;
}
So for this code, I either want to use a random number as the pivot for the partitioning step, or use the median of the first, middle, and last elements as the pivot.
How would I do this?
I'm new to sorting algorithms, and my understanding of them is not complete just yet.