快排非递归算法

复制代码
#include<bits/stdc++.h>
using namespace std;
const int maxn=1010;
int getP(int num[],int left,int right){
    int temp=num[left];
    while(left<right){
        while(left<right&&num[right]>=temp){
            right--;
        }
        num[left]=num[right];
        while(left<right&&num[left]<=temp){
            left++;
        }
        num[right]=num[left];
    }
    num[left]=temp;
    return left;
}
void quicksort(int num[],int left,int right){
    if(left<right){
    int pivot=getP(num,left,right);
/**  递归实现
     quicksort(num,left,pivot-1);
    quicksort(num,pivot+1,right);
*/
    stack<int> st;
    st.push(left);
    st.push(right);
    while(!st.empty()){
        int p=st.top();
        st.pop();
        int q=st.top();
        st.pop();
        pivot=getP(num,q,p);
        if(q<pivot-1){
            st.push(left);
            st.push(pivot-1);
        }
        if(p>pivot+1){
            st.push(pivot+1);
            st.push(right);
        }
    }
}
}
int main(){
    int num[maxn];
    int n;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>num[i];
    }
    quicksort(num,0,n-1);
    for(int i=0;i<n;i++){
        cout<<num[i]<<" ";
    }
    cout<<endl;
}
复制代码

原理:

利用栈循环保存子区间的边界,然后弹出边界找中枢pivot

posted @   XA科研  阅读(70)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2021-03-05 1038 Recover the Smallest Number (30 分)
2021-03-05 1067 Sort with Swap(0, i) (25 分)
2021-03-05 1037 Magic Coupon (25 分)
2021-03-05 随笔(五)
2021-03-05 1070 Mooncake (25 分) 贪心
点击右上角即可分享
微信分享提示