您的位置:首页 > 理论基础 > 数据结构算法

数据结构:快速排序

2018-02-25 15:46 148 查看

快速排序

思路是这样的,找到一个key然后对数组做遍历比key小的都放到key的左边,比key大的都在key的右边,然后依次递归即可

代码如下

#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>
#include <iomanip>

using namespace std;

int part(int a[], int beg, int fin)
{
int key = a[beg];
int first = beg;
int last = fin;
while (first<last)
{
while (first<last && a[last] >= key)
last--;
a[first] = a[last];
while (first<last && a[first] <= key)
first++;
a[last] = a[first];
}
a[first] = key;
return first;
}

void qsort(int a[], int beg, int fin)
{
if (beg<fin)
{
int key = part(a, beg, fin);
qsort(a, beg, key - 1);
qsort(a, key + 1, fin);
}
else
return;
}

void outa(int a[], int len)
{
for (int i = 0; i < len; i++)
cout << a[i] << "   ";
cout << endl;
}
void main()
{
int c;
int a[10] = { 9,8,7,6,5,4,3,2,1,0 };
cout << "排序前:";
outa(a, 10);
qsort(a, 0, 9);
cout << "排序后: ";
outa(a, 10);
system("pause");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: