快速排序也是使用了分治策略(递归),每一次遍历时将队列分为三部分:
- 基准元素
- 不大于基准元素的部分
- 大于基准元素的部分
对于不大于基准元素的部分和大于基准元素的部分,再次排序过程正好是整个排序的一个子过程。
如果每次选择的基准元素使得剩余部分都分部在基准元素的单侧,则是快速排序性能的最坏情况,时间复杂度为 。
如果每次选择的基准元素使得剩余部分元素均衡的分布在基准元素两侧,则是快速排序性能最好的情况,时间复杂度为。
快速排序的平均运行时间更接近于最好的情况,而非最坏的情况,而且其隐含的常数因子非常小,而且能够进行原址排序,是大数组排序最常用的算法。
#include "QuickSort.h"
#include "Common.h"
using namespace std;
void QuickSort(int* A, int start, int end)
{
if (end - start > 1)
{
int mid = Partition(A, start, end);
QuickSort(A, start, mid);
QuickSort(A, mid + 1, end);
}
}
int Partition(int* A, int start, int end)
{
int x = A[end - 1];
int i = start - 1;
for (auto j = start; j < end - 1; j++)
{
if (A[j] <= x)
{
Exchange(A, ++i, j);
}
}
Exchange(A, ++i, end - 1);
return i;
}
void RandomizedQuickSort(int* A, int start, int end)
{
if (end - start > 1)
{
int mid = RandomizedPartition(A, start, end);
RandomizedQuickSort(A, start, mid);
RandomizedQuickSort(A, mid + 1, end);
}
}
int RandomizedPartition(int* A, int start, int end)
{
int i = Random(start, end);
Exchange(A, i, end - 1);
return Partition(A, start, end);
}
void TestQuickSort()
{
int a[] = { 2, 8, 7, 1, 3, 5, 6, 4 };
int len = sizeof(a) / sizeof(int);
QuickSort(a, 0, len);
Print(a, len);
}
void TestRandomizedQuickSort()
{
int a[] = { 2, 8, 7, 1, 3, 5, 6, 4 };
int len = sizeof(a) / sizeof(int);
QuickSort(a, 0, len);
Print(a, len);
}
输出:
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
E:\GitHub\IntroductionToAlgorithms\C++\build\Debug\IntroductionToAlgorithms.exe (进程 34260)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .