演算法設計之快速排序
阿新 • • 發佈:2021-01-19
技術標籤:演算法設計
思想
採用了分而治之的思想
演算法步驟為:
程式碼:
#include<iostream>
using namespace std;
int GetMid(int a[],int nlow,int nhigh)
{
int nleft = nlow;
int nright = nhigh;
int npivot = a[nlow];//對比的值
while (nleft<nright)
{
//1.右邊的先向左掃描,找到比npivot小的數然後放到left位置
while (a[nright]> npivot && nright>nleft)
{
nright--;
}
a[nleft] = a[nright];
//2.左邊的先向右掃描,找到比npivot大的數然後放到右邊right位置
while (a[nleft] < npivot && nleft <nright)
{
nleft++;
}
a[nright] = a[nleft];
}
//3.nleft 和 nright 指向相同的位置時,使其npivot的值指向該位置。
a[nleft] = npivot;
//4.返回中間分隔的位置
return nleft;
}
void quicksort(int a[],int nlow,int nhigh)
{
if (nlow<nhigh)
{
int nmid = GetMid(a, nlow, nhigh);//得到分隔位置
quicksort(a, nlow, nmid - 1);//排序分隔位置左邊的子序列
quicksort(a, nmid + 1, nhigh);//排序分隔位置右邊的子序列
}
}
void main()
{
int a[] = { 30, 24, 5, 58, 18, 36, 12, 42, 39};
cout << "原陣列:" ;
for (auto node :a)
{
cout << node << " ";
}
cout << endl;
cout << "排序後:";
quicksort(a, 0, sizeof(a) / sizeof(a[0]) - 1);
for (auto node :a)
{
cout << node << " ";
}
cout << endl;
int b[] = { 30, 24, 5, 58, 18, 36, 12, 42, 39,2,8,89,17 };
cout << "原陣列:";
for (auto node : b)
{
cout << node << " ";
}
cout << endl;
cout << "排序後:";
quicksort(b, 0, sizeof(b) / sizeof(b[0]) - 1);
for (auto node : b)
{
cout << node << " ";
}
cout << endl;
system("pause");
}
結果:
快速排序法最好的時間複雜度為o(nlogn),最壞的情況下就成了氣泡排序,時間複雜度為o(n^2)