1.简介
分治和递归
三数中值分割
最坏时间为O(N2)
最好时O(NlogN)
平均情况O(NlogN)
2.实现
/*快速排序*/
ElementType Median3(ElementType A[], int Left, int Right)
{
/*A[left] <= A[Center] <= A[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]);
}
/* 将枢纽元移到Right-1处 */
Swap(&A[Center], &A[Right - 1]);
return A[Right - 1];
}
#define Cutoff (3)
void Qsort(ElementType A[], int Left, int Right)
{
int i, j;
ElementType Privot;
if (Left + Cutoff <= Right)
{
Privot = Median3(A, Left, Right);
i = Left; j = Right - 1;
for (;;)
{
while (A[++i] < Privot){}
while (A[--j] > Privot){}
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
/*Do an insertion sort on the small array*/
InsertionSort(A + Left, Right - Left + 1);
}
void Quicksort(ElementType A[], int N)
{
Qsort(A, 0, N - 1);
}