快速排序quickSort
#include <iostream>
#include <vector>
using namespace std;
int findPivot(vector<int> &a, int lo, int hi)
{
int ce = (lo + hi) / 2;
if (a[lo] > a[ce])
swap(a[lo], a[ce]);
if (a[lo] > a[hi])
swap(a[lo], a[hi]);
if (a[ce] > a[hi])
swap(a[ce], a[hi]);
swap(a[ce], a[hi - 1]);
return a[hi-1];
}
void qSort(vector<int> &a, int lo, int hi)
{
if (hi <= lo)
return;
if (hi - lo == 1)
{
if(a[lo]>a[hi])
swap(a[lo], a[hi]);
return;
}
int pivot = findPivot(a, lo, hi);
int i = lo, j = hi-1; //注意j取值
while (1)
{
while (a[++i] < pivot);
while (a[--j] > pivot);
if (i < j)
swap(a[i], a[j]);
else
break;
}
swap(a[i], a[hi - 1]);//还原pivot
qSort(a, lo, i - 1);
qSort(a, i + 1, hi);
}
void quickSort(vector<int> &a)
{
qSort(a, 0, a.size() - 1);
}
int main()
{
vector<int> a{ 10, 2, 3, 7, 1, 6, 4, 9, 2 };
quickSort(a);
for (auto &ele : a)
cout << ele << " ";
return 0;
}