快排算法
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int partition(vector<int> &vec, int left, int right){
int element = vec[left]; //选择最左边元素为轴点
int i, j;
// i指向大于element的第一个元素
for (i = left + 1, j = left + 1; j <= right;){
if (vec[j] >= element){
j++;
}
else{
swap(vec[j], vec[i]);
i++;
j++;
}
}
i--; // 需要i--
swap(vec[left], vec[i]);
// cout << i << endl;
return i;
}
void quick_sort(vector<int> &vec, int left, int right){
// 快排:分治思想,根据轴点将数组分成左右两个部分,依次解决
if (left >= right)
return;
int index = partition(vec, left, right);
quick_sort(vec, left, index - 1);
quick_sort(vec, index + 1, right);
}
int main(){
vector<int> vec = {5, 3, 2, 6, 1, 2};
quick_sort(vec, 0, vec.size() - 1);
//partition(vec, 0, 4);
for (auto i:vec)
cout << i << endl;
return 0;
}