/****
****采用三数中值法选区枢纽元
****在数据小于一定值时采用插入排序可以实现更高效率的排序
****
****
****
****
****/
#include <iostream>
#define cutoff 3
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
template <class Type>
void swap(Type &a, Type &b)
{
Type temp;
temp = a;
a = b;
b = temp;
}
template<class Type>
void InsertSort(Type A[], int N)
{
int i, j;
Type temp;
for (i = 1; i<N; i++)
{
temp = A[i];
for (j = i; j >= 0 && A[j - 1]>temp; j--)
A[j] = A[j - 1];
A[j] = temp;
}
}
//以三数中值作为基准值
template <class Type>
Type Median3(Type A[], int left, int right)
{
int center = (left + right) / 2;
if (A[left]>A[center])
swap(A[left], A[center]);
if (A[left]>A[right])
swap(A[left], A[right]);
if (A[center]>A[right])
swap(A[center], A[right]);
//以上得到A[left]<=A[center]<=A[right]
swap(A[center], A[right - 1]);//隐藏枢纽元
return A[right - 1]; //返回枢纽元
}
template <class Type>
void QSort(Type A[], int left, int right)
{
int i, j;
Type Pivot;
Pivot = Median3(A, left, right);
i = left; j = right - 1;
if (left + cutoff <= right)
{
for (;;)
{
while (A[++i]<Pivot){}
while (A[--j]>Pivot){}
if (i<j)
swap(A[i], A[j]);
else
break;
}
swap(A[i], A[right - 1]);//将枢纽元换回
QSort(A, left, i - 1);
QSort(A, i + 1, right);
}
else
InsertSort(A+left,right-left+1);
}
int main(int argc, char *argv[]) {
int A[10] = { 2, 5, 1, 3, 43, 6,21,32,78,76 };
QSort(A, 0, 9);
//QSort();
//swap(A[0],A[1]);
for (int i = 0; i<10; i++)
std::cout << A[i] << std::endl;
return 0;
}