快排 随机分割

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

#include<iostream>
#include <stdlib.h> 
using namespace std;
inline void swap(int &a, int &b)
{
    int c = a;
    a = b;
    b = c;
}
//随机分割
int Random(int a, int b)//随机在a--b选择一个整数
{
    return a + rand() % (b - a + 1);
}
template<class type>
int RandomizedPartition(type a[], int p, int r)//随机分割
{
    int i = Random(p, r);//在p--r中随机选择一个数
    swap(a[i], a[p]);
    return Partition(a, p, r);
}
template<class type>
int Partition(type a[], int p, int r)//以随机选的那个数作为分割起点,p此时是之前随机选的a[i]的位置;
{
    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 RandomizedQuickSort(type a[], int p, int r)
{
    if (p < r)
    {
        int q = RandomizedPartition(a, p, r);
        RandomizedQuickSort(a, p, q - 1);//左半端排序
        RandomizedQuickSort(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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值