快速排序 一般分割

计算机算法设计与分析第四版[王]

    #include<iostream>
    #include <stdlib.h> 
    using namespace std;
    inline void swap(int &a, int &b)
    {
        int c = a;
        a = b;
        b = c;
    }
    //一般分割
    template<class type>
    int Partition(type a[], int p, int r)//以第一个位置作为分割起点
    {
        int i = p, j = r + 1;
        type x = a[p];
        while (true)
        {
            while (a[++i] < x&&i < r);
            while (a[--j] > x);
            if (i >= j) break;
            swap(a[i], a[j]);
        }
        a[p] = a[j];
        a[j] = x;
        return j;//返回结束后分割点所在的位置
    }
    template<class type>
    void QuickSort(type a[], int p, int r)
    {
        if (p < r)
        {
            int q = Partition(a, p, r);
            QuickSort(a, p, q - 1);//对右边排序
            QuickSort(a, q + 1, r);//对左边排序
        }
    }
    int main()
    {
        int a[] = { 5,1,66,44,87,32,12,66,99,45,32,156,456 };
        RandomizedQuickSort(a, 0, 12);
        for (int i = 0;i < 12;i++)
        {
            cout << a[i] << endl;
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值