快排的递归和非递归C++

#include<iostream>
#include<vector>
using namespace std;
//递归版本
void quickSort(int A[],int s,int t){
    if (s >= t){
        return;
    }
    int i = s;
    int j = t + 1;
    while (true){
        do{
            i++;
        } while (A[i] < A[s]&&i<t);
        do{
            j--;
        } while (A[j] > A[s]&&j>s);
        if (i < j){
            std::swap(A[i], A[j]);
        }
        else{
            std::swap(A[s], A[j]);
            break;
        }
    }
    quickSort(A, s, j-1);
    quickSort(A, j+1 , t);
}
//非递归版本
class node{
public:
    int start = 0;
    int end = 0;
    node(int _start,int _end){
        start = _start;
        end = _end;
    }
};
void quickSort(int A[],node node0){
    vector<node> STACK;
    int s = -1;
    int t = -1;
    STACK.push_back(node0);
    while (true){
        if (STACK.empty()){
            return;
        }
        else{
            node tmp = STACK.back();
            STACK.pop_back();
            s = tmp.start;
            t = tmp.end;
            if (s >= t){
                continue;
            }
        }
        int i = s;
        int j = t + 1;
        while (true){
            do{
                i++;
            } while (A[i]<A[s] && i < t);
            do{
                j--;
            } while (A[j] > A[s] && j>s);
            if (i < j){
                std::swap(A[i], A[j]);
            }
            else{
                std::swap(A[s], A[j]);
                break;
            }
        }
        STACK.push_back(node(s,j-1));
        STACK.push_back(node(j+1,t));
    }

}
int main(){
    int A[] = { -1, -2, -3, -4, -5 };
    quickSort(A, 0, 4);  //递归
    int B[] = { -1, -2, -3, -4, -5 };
    quickSort(B, node(0, 4));
    cout << "递归" << endl;
    for (int i = 0; i < 5; ++i){
        cout << A[i] << endl;
    }
    cout << "非递归" << endl;
    for (int i = 0; i < 5; ++i){
        cout << B[i] << endl;
    }
    system("pause");
}

 

转载于:https://www.cnblogs.com/codeDog123/p/6642265.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值