算法导论 第2版 7.3 快速排序随机化版本

根据书上伪码编写:

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

int A[11] = {-1,4,1,8,3,10,2,5,6,9,7};//下标从1开始,因此A[0]不用,用-1标记
int n = sizeof(A)/sizeof(int)-1;

int partition(int *A, int p, int r)//划分函数
{
    int x = A[r];
    int i = p-1;
    int temp;
    for(int j = p; j<=r-1; j++)
    {
        if(A[j] <= x)
        {
            i++;
            temp = A[i];
            A[i] = A[j];
            A[j] = temp;
        }
    }
    temp = A[i+1];
    A[i+1] = A[r];
    A[r] = temp;
    return i+1;
}

int randomized_partition(int *A, int p, int r)//从A[p]~A[r]中随机选择pivot
{
    int temp;
    int i = rand()%(r-p) + p;//生成p到r之间的随机数
    //原理:对于任意整数r,p有:0 <= rand()%(r-p+1) <= r-p
    //于是:0+p <= rand()%(r-p+1)+p <= r-p+p
    //即:p <= rand()%(r-p+1)+p <= r
    temp = A[r];
    A[r] = A[i];
    A[i] = temp;
    return partition(A, p, r);//调用划分函数
}

void ramdomized_quicksort(int *A, int p, int r)//随机快速排序的主体函数
{
    if(p < r)
    {
        int q = randomized_partition(A, p, r);//生成pivot,赋给q
        ramdomized_quicksort(A, p, q-1);//分治法,递归调用自身
        ramdomized_quicksort(A, q+1, r);
    }
}

int main()
{
    //根据系统时间设置随机数种子
    srand( (unsigned)time(NULL) );
    ramdomized_quicksort(A, 1, n);//对A[1...n]进行原地快排
    for(int i = 0; i<=n; i++)//输出
        cout << A[i] << " ";
}

输出:-1 1 2 3 4 5 6 7 8 9 10

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值