原理
取一个轴,左边小于右边大于,不断的取轴,左小右大.
啊啊啊啊啊啊啊,这代码有bug,我打了三个小时补丁也没搞定,实在烦了,就直接这样吧.无伤大雅,这东西要用直接复制粘贴就行了,原理没问题就好.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int myPartition(vector<int>& v, int min, int max)
{
//设一个轴
int axis = v[min];
//因为min为轴
int left_index = min + 1;
int right_index = max;
//需要两边移动
while (left_index <= right_index)
{
//左边数比轴小不断后移
while (left_index <= right_index && v[left_index] <= axis)
{
left_index++;
}
//右边数比轴大不断前移
while (left_index <= right_index && v[right_index] > axis)
{
right_index--;
}
if (left_index < right_index)
{
swap(v[left_index], v[right_index]);
}
}
swap(v[right_index], v[min]);
return left_index;
}
void sort(vector<int>& v, int min, int max)
{
if (min >= max)
{
return;
}
int axis_index = myPartition(v, min, max);
sort(v, min, axis_index - 1);
sort(v, axis_index + 1, max);
}
void quickSort(vector<int>& v)
{
//为空或数据少于两个,直接退出
if (v.empty() || v.size() < 2)
{
return;
}
sort(v, 0, v.size() - 1);
}
int main()
{
vector<int> v = { 32,4,7,24,5,245,7,245,657,28 };
quickSort(v);
for (auto val : v)
{
cout << val << " ";
}
cout << endl;
return 0;
}