Monday, October 27, 2008

Median of Three Quick Sort

#ifndef MEDIAN3QUICKSORT
#define MEDIAN3QUICKSORT

#include
#include "InsertionSort.h"

namespace mystd
{
template
void Median(T* sortee, T* pivotValue,
int left, int right)
{
int middle = (left + right) / 2 ;

if (*(sortee + left) > *(sortee + middle))
{
std::swap(*(sortee + left),
*(sortee + middle));
}

if (*(sortee + left) > *(sortee + right))
{
std::swap(*(sortee + left),
*(sortee + right));
}

if (*(sortee + middle) > *(sortee + right))
{
std::swap(*(sortee + middle),
*(sortee + right));
}

// Put middle element in right - 1
std::swap(*(sortee + middle),
*(sortee + right -1));

*pivotValue = *(sortee + right -1);

}

template
void Partition(T* sortee, T* pivotValue,
int left, int right)
{
int leftIncrement = left;
int rightDecrement = right - 1;

while(leftIncrement <> *pivotValue)
{
}

if (leftIncrement <>
int FindIndex(T* sortee, T pivotValue,
int right)
{
int pivotIndex = 0;

for (int loop=0;loop
void M3QuickSort(T* sortee, int left, int right)
{
int size = right;
const int CUTOFF = 0; T pivotValue = 0, pivotIndex = 0;

if (left + CUTOFF < right)
{
Median(sortee, &pivotValue, left, right);
Partition(sortee, &pivotValue, left, right);

pivotIndex = FindIndex(sortee, pivotValue, right);

M3QuickSort(sortee, left, pivotIndex - 1);
M3QuickSort(sortee, pivotIndex + 1, right);
}
}

}

#endif

No comments: