算法 | 快速排序

【算法图解】:数据结构教程李春葆版P378

1.  递归代码:

#include<iostream>
#include<vector>
using namespace std;

void quicksort(vector<int> &v, int left, int right)
{
    if (left < right)
    {
        int key = v[left];
        int low = left;
        int high = right;
        while (low < high)
        {
            while(low < high && v[high] >= key)
                high--;
            v[low] = v[high];

            while (low < high && v[low] < key)
                low++;
            v[high] = v[low];
        }
        v[low] = key;
        quicksort(v, left, low - 1);
        quicksort(v, low + 1, right);
    }
}

int main()
{
    vector<int> num = { 6, 8, 7, 9, 0, 1, 3, 2, 4, 5 };
    quicksort(num, 0, num.size() - 1);
    for (auto c : num)
        cout << c << " ";
    cout << endl;
    return 0;
}

2. 非递归版本:

#include<iostream>
#include<vector>
#include<stack>
using namespace std;

void quicksort(vector<int> & arr, int length)
{
    stack<int> lowHigh;//先存大再存小,取得时候就可以先取小再取大,此处的大小指的是数组索引
    lowHigh.push(length - 1);
    lowHigh.push(0);
    int low, high;
    while (!lowHigh.empty())
    {
        low = lowHigh.top(); 
        lowHigh.pop();
        high = lowHigh.top(); 
        lowHigh.pop();
        if (low >= high)
            continue;
        int i = low; 
        int j = high;
        int value = arr[low];
        while (i < j)//i==j循环结束
        {
            while (arr[j] > value)
                j--;//右边的都大于value
            std::swap(arr[j], arr[i]);
            while (arr[i] < value)
                i++;//左边的都小于value
            std::swap(arr[i], arr[j]);
        }
        //开始存储左右两侧待处理的数据,为了先处理左侧先保存右侧数据
        lowHigh.push(high);
        lowHigh.push(i + 1);
        //左侧
        lowHigh.push(i - 1);
        lowHigh.push(low);
    }
}

int main()
{
    vector<int> data = { 6, 8, 7, 9, 0, 1, 3, 2, 4, 5 };
    quicksort(data, data.size());
    for (int i = 0; i < 10; ++i)
        printf("%d ", data[i]);
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值