I'm trying to implement quicksort and I am following steps in my book and I don't understand how the median of three should be implemented. I followed book instructions but I don't understand why the median of three actually helps with? I never actually do anything with it.
Here is my implementation:
Herer is my Quicksort implementation.
void QuickSort::QuickSortM3(std::vector<int> &data, int left, int right){
if(left < right){
pivotM3(data, left, right);
int i = partition(data, left, right);
QuickSortM3(data, left, i-1);
QuickSortM3(data, i +1, right);
}
}
void QuickSort::pivotM3(std::vector<int> &data, int left, int right){
std::swap(data[(left+ right)/2], data[(right -1)]);
if(data[left] < data[right-1]){
std::swap(data[left], data[right-1]);
}
if(data[left] < data[right]){
std::swap(data[left], data[right]);
}
if(data[right -1] < data[right]){
std::swap(data[left], data[right-1]);
}
}
int QuickSort::partition(std::vector<int> &data, int left, int right){
int i = left - 1, j = right; int v = data[right];
for(;;){
while(data[++i] < v);
while (v < data[--j]){
if( j == left) {
break;
}
}
if(i >= j) break;
std::swap(data[i], data[j]);
}
std::swap(data[i], data[right]);
return i;
}
What I actually mean is, should I not be using the middle element in the partitioning? Any help would be great, thank you.