这个程序参考了STL , 侯捷注
快速排序进行递归时, 当元素个数小于一定值(5~20), 会采用插入排序,本程序没有用这种方法,过几天再写一个。
#include <iostream>
#include <vector>
#include <algorithm>
using std::cout;
using std::endl;
using std::vector;
using std::swap;
//找枢轴,这里采用中值, 也可采用随机选取
int median(const int& a, const int& b, const int& c)
{
if ((a <= b && b <= c) || (a >= b && b >= c))
return b;
else if ((a <= c && c <= b) || (a >= c && c >= b))
return c;
else
return a;
}
//进行分割, 小于枢轴的元素排到左边, 大于枢轴的元素右边
vector<int>::iterator
partition(vector<int>::iterator first, vector<int>::iterator last, int pivot)
{
while (true)
{
while (*first < pivot)
++first;
--last;
while (pivot < *last)
--last;
if (!(first < last))
return first;
swap(*first, *last);
++first;
}
}
//递归
void QuickSort(vector<int>::iterator first, vector<int>::iterator last)
{
if (last - first > 1)
{
int med = median(*first, *(first + (last - first) / 2), *(last - 1));
auto cut = partition(first, last, med);
QuickSort(first, cut);
QuickSort(cut, last);
}
}
int main()
{
vector<int> arr{ 2, 6, 1, 0, 8, 5 , 6, 3, 11};
QuickSort(arr.begin(), arr.end());
for (auto& i : arr)
cout << i << " ";
cout << endl;
return 0;
}