程序员的诞生(一):排序——快速排序

算法思想

快速排序是一种交换排序,它的基本思想是:先选一个元素作为基准,将大于它的元素都放到它的右边,小于它的元素都放到它的左边,然后在它的左右两边再各找一个基准,同样让这个两个基准的左右两边都满足左边都小于自己,右边都大于自己,以此循环往复下去,直到不能再分。

算法实现

#include<iostream>
#include<vector>

using namespace std;

int Partition(vector<int> &v, int low, int high);
void QuickSort(vector<int> &v, int low, int high);

int main()
{
    vector<int> v{12,3,5,1,34,9,23,16,38,8,6};
    for (auto i : v)
    {
        cout << i << " ";
    }
    cout << endl;

    QuickSort(v, 0, v.size()-1);

    for (auto i : v)
    {
        cout << i << " ";
    }
    cout << endl;

    while (1);
    return 0;
}

void QuickSort(vector<int> &v, int low, int high)
{
    int p;
    if (low < high)
    {
        p = Partition(v, low, high);
        QuickSort(v, low, p-1);
        QuickSort(v, p+1, high);
    }
}

int Partition(vector<int> &v, int low, int high)
{
    int base = v[low];
    int temp;
    while (low < high)
    {
        while (low < high && v[high] >= base)
        {
            --high;
        }
        v[low] = v[high];

        while(low < high && v[low] <= base)
        {
            ++low;
        }
        v[high] = v[low];
    }
    v[low] = base;
    return low;
}

程序运行结果如下图:

这里写图片描述

上面这种写法也是很主流的一种写法,利用递归的方法,整个代码简介紧凑。特在此记录,以备不时之需。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值