C++ 快排递归实现和非递归实现

Posted fulianzhou

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++ 快排递归实现和非递归实现相关的知识,希望对你有一定的参考价值。

#include <stdint.h>
#include <list>
#include <stack>
#include <vector>
#include <time.h>

using namespace std;

int cnt1 = 0;
int cnt2 = 0;
int *idx_stack;
void QuickSort(vector<int>& arr, int left, int right)

    if (left >= right)
    
        return;
    
    cnt1++;

    int l = left;
    int r = right;

    //printf("[%d, %d]\\n", left, right);

    int pivot = arr[l];

    while (l < r)
    
        while (arr[r] >= pivot && l < r) r--;
        arr[l] = arr[r];

        while (arr[l] <= pivot && l < r) l++;
        arr[r] = arr[l];
    

    arr[l] = pivot;

    QuickSort(arr, left, l - 1);
    QuickSort(arr, r + 1, right);


void QuickSortNoRecurve(vector<int>& arr, int left, int right)

    int idx_start = right - 1;
    idx_stack[idx_start--] = right;
    idx_stack[idx_start--] = left;
    
    while (idx_start < right - 1)
    
        cnt2++;
        int _left = idx_stack[++idx_start];
        int _right = idx_stack[++idx_start];

        //printf("[%d, %d]\\n", _left, _right);

        int l = _left;
        int r = _right;

        int pivot = arr[l];

        while (l < r)
        
            while (arr[r] >= pivot && l < r) r--;
            arr[l] = arr[r];

            while (arr[l] <= pivot && l < r) l++;
            arr[r] = arr[l];
        

        arr[l] = pivot;

        if (_left < l - 1)
        
            idx_stack[idx_start--] = (l - 1);
            idx_stack[idx_start--] = (_left);
        

        if (r + 1 < _right)
        
            idx_stack[idx_start--] = (_right);
            idx_stack[idx_start--] = (r + 1);
        
    


void genData(vector<int>& arr, int num)

    srand(time(0));

    arr.resize(num);
    for (int i = 0; i < num; i++)
    
        arr[i] = rand() % 20;
    


int main(int argc, char* argv[])

    vector<int> arr;
    genData(arr, 10000);

    idx_stack = new int[arr.size()];

    int start1 = time(0);
    for (int i = 0; i < 10000; i++)
    
        vector<int> arr1 = arr;
        QuickSort(arr1, 0, arr1.size() - 1);
    
    int start2 = time(0);

    int start3 = time(0);
    for (int i = 0; i < 10000; i++)
    
        vector<int> arr2 = arr;
        QuickSortNoRecurve(arr2, 0, arr2.size() - 1);
    
    int start4 = time(0);

    printf("%d %d %d %d\\n", start2 - start1, cnt1, start4 - start3, cnt2);

    return 0;

递归输出:

非递归输出:

以上是关于C++ 快排递归实现和非递归实现的主要内容,如果未能解决你的问题,请参考以下文章

快排的递归和非递归

力扣784. 字母大小写全排列 回溯法 C++递归和非递归俩种实现非方式

C++ 不知树系列之二叉堆排序(递归和非递归实现上沉下沉算法)

快排---非递归实现

快排(golang实现) 递归方法

go 递归实现快排