思路:
1.快排是递归调用,传入左右边界值,递归调用本质也是栈,先进后出
2.向栈中压入左右边界值实现快速排序
#include<iostream>
#include<vector>
#include<array>
#include<stack>
using namespace std;
void sort1(vector<int>& v) {
stack<std::array<int, 2>> s{};
s.push({ 0,v.size() - 1 });
while (!s.empty()) {
std::array<int, 2> a{ s.top() };
s.pop();
if (a[0] < a[1]) {
int left = a[0], right = a[1];
int pos = v[left];
while (left < right) {
while (left < right && v[right] >= pos) right--;
if (left < right) v[left++] = v[right];
while (left < right && v[left] <= pos) left++;
if (left < right) v[right--] = v[left];
}
v[left] = pos;
s.push({ a[0],left - 1 });
s.push({ left + 1,a[1] });
}
}
}
int main()
{
vector<int> v{ 1,3,5,1,2 };
sort1(v);
for (int i = 0; i < v.size(); i++) {
cout << v[i] << endl;
}
getchar();
return 0;
}