參考資料:
[1]啊哈槐脏!算法 第3節(jié) 最常用的排序--快速排序(特別形象)
[2]http://www.cnblogs.com/skywang12345/p/3596746.html
#include<iostream>
using namespace std;
void QuickSort(int *a, int nLeft, int nRight)
{
if (a == nullptr || nLeft > nRight)
return;
//定義1個基準點拓挥,然后從右往左找第一個小于基準點的數(shù)瓷患,再從左往右找第一個大于基準點的數(shù)
//如果兩個哨兵相遇翔悠,那么就和基準值相換
int nTmp = a[nLeft];
int i = nLeft;
int j = nRight;
while (i != j)
{
while (a[j] >= nTmp && i < j)
{
j--;
}
while (a[i] <= nTmp && i < j)
{
i++;
}
if (i != j)
{
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
a[nLeft] = a[i];
a[i] = nTmp;
QuickSort(a,nLeft,i-1);
QuickSort(a,i+1,nRight);
}
int main()
{
int a[10] = {10,9,8,6,5,3,2,1,4,7};
int nLen = sizeof(a) / sizeof(a[0]);
cout << nLen<<endl;
for (int i = 0; i < nLen; i++)
{
cout << a[i] << " ";
}
cout << endl;
//BubbleSort(a,nLen);
QuickSort(a,0,nLen-1);
for (int i = 0; i < nLen; i++)
{
cout << a[i] << " ";
}
system("pause");
}
快速排序的復雜度最壞情況下和冒泡排序是一樣的,為O(N^2)拟杉。平均時間復雜度為O(N*logN)翅娶。