非递归快排
通过使用栈来模拟函数栈的调用,每次将首尾指针存入到栈中,并对首尾之间区域进行快排。
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
//利用栈将序列的起始和末尾保存起来
int partition(vector<int> &v, int s, int e)
{
int i = s;
int j = e;
while(i < j){
while(j > i && v[j] >= v[s]) j--;
while(j > i && v[i] <= v[s]) i++;
swap(v[i], v[j]);
}
swap(v[s], v[i]);
return i;
}
void quickSort(vector<int> v, int s, int e)
{
if(s >= e) return ;
stack<int> st; //用来存储起始和末尾点的栈
st.push(s);
st.push(e);
while(!st.empty()){
int r = st.top();
st.pop();
int l = st.top();
st.pop();
if(l < r){
int m = partition(v, l, r);
st.push(l);
st.push(m);
st.push(m + 1);
st.push(r);
}
}
for(auto it : v)
cout << it << ' ';
cout << endl;
}
int main()
{
int arr[] = {13,65,97,76,38,27,49};
vector<int> vec(arr, arr + sizeof(arr)/4);
quickSort(vec, 0, vec.size() - 1);
return 0;
}