非递归快排

非递归快排

通过使用栈来模拟函数栈的调用,每次将首尾指针存入到栈中,并对首尾之间区域进行快排。

#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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值