递归和非递归快速排序算法实现

快速排序

快速排序算法核心思想,在快速排序过程中,通过一趟划分,可以把待排序区间分为两个子区间,然后分别对这两个子区间再进行同样的划分,这样的套娃机制我们常常使用递归算法解决比较轻松,不过也可以通过非递归的方法实现。比如我们下面讲到的非递归算法,分别使用了栈,还有队列实现,以栈为例,栈的作用就是在处理一个子区间的时候,保存产生的新的左、右区间,待一个区间处理完后,再从栈中取出另外一个子区间进行处理

  1. 递归算法实现
  2. 栈实现
  3. 队列实现
//  快速排序的两种实现方式1-递归2-非递归

#include <stdio.h>
using namespace std;
#include<iostream>
#include<queue>

queue<int>q;

#include<stack>

stack<int>s;

void print_data(int A[], int n){
//    cout << "下标从0开始:";
    for (int i = 0; i<n; i++) {
        cout << A[i] << " ";
    }
    cout << endl << endl;
}
int do_quick_sort(int A[], int low, int high);
void quick_sort(int A[], int low, int high){
    if (low<high) {
        //返回中间位置
        int mid = do_quick_sort(A, low, high);
//        cout << "mid:" << mid << endl;
        quick_sort(A, low, mid-1);
        quick_sort(A, mid+1, high);
    }
}
int do_quick_sort(int A[], int low, int high){
    int temp = A[low];
  
    while(low<high){
        while(low<high && temp<=A[high])
            high--;
        A[low] = A[high];
        while(low<high && temp>A[low])
            low++;
        A[high] = A[low];
    }

    A[high] = temp;
    return high;
}

void quick_sort2(int A[], int low, int high){
    s.push(low);
    s.push(high);
    int high1 = 0, low1 = 0;
    while (!s.empty()) {
        high1 = s.top();
        s.pop();
        low1 = s.top();
        s.pop();
        int mid = do_quick_sort(A, low1, high1);
        if (low1<=mid-1) {
            s.push(low1);
            s.push(mid-1);
        }
        if (mid+1<=high1) {
            s.push(mid+1);
            s.push(high1);
        }
        
    }
}


void quick_sort3(int A[], int low, int high){
    q.push(low);
    q.push(high);
    int high1 = 0, low1 = 0;
    
    while (!q.empty()) {
        low1 = q.front();
        q.pop();
        high1 = q.front();
        q.pop();
        int mid = do_quick_sort(A, low1, high1);
        if (low1<=mid-1) {
            q.push(low1);
            q.push(mid-1);
        }
        if (mid+1<=high1) {
            q.push(mid+1);
            q.push(high1);
        }
        
    }
}
int main(){
    cout << "welcome, to my world!" << endl;
    int A[] = {5,3,6,8,2,6,9,73,985,211};
    print_data(A, 10);
    quick_sort(A, 0, 9);
    print_data(A, 10);
    quick_sort2(A, 0, 9);
    print_data(A, 10);
    quick_sort3(A, 0, 9);
    print_data(A, 10);
    return 0;
}

输出

welcome, to my world!
5 3 6 8 2 6 9 73 985 211

2 3 5 6 6 8 9 73 211 985

2 3 5 6 6 8 9 73 211 985

2 3 5 6 6 8 9 73 211 985

Program ended with exit code: 0

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值