随机化快速排序

本文详细介绍了一种改进的快速排序算法——随机化快速排序。通过使用随机选择枢轴的方法,该算法能有效避免最坏情况的发生,提高排序效率。文章提供了完整的C++代码实现,包括随机数生成、元素交换、分区操作以及递归调用等关键步骤。
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;

int random(int a,int b)
{
srand(NULL);
return rand()%(b-a)+a;
}


void exchange(int &a,int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}

int partition(int *a,int p,int r)
{
int x=a[r];
int i=p-1;
for (int j=p;j<r;j++)
{
if (a[j]<=x)
{
i=i+1;
exchange(a[i],a[j]);
}
}
exchange(a[i+1],a[r]);
return i+1;
}

int randomized_partition(int *a,int p,int r)
{
int i=random(p,r);
exchange(a[r],a[i]);
return partition(a,p,r);
}

void randomized_quicksort(int *a,int p,int r)
{
int q;
if (p<r)
{
q=randomized_partition(a,p,r);
randomized_quicksort(a,p,q-1);
randomized_quicksort(a,q+1,r);
}
}

int main()
{
int a[]={4,1,3,2,16,30,10,14,15,4,6,8,0};
int length=sizeof(a)/sizeof(int)-1;
randomized_quicksort(a,0,length);

for (int i=0;i<=length;i++)
cout<<a[i]<<"";

system("pause");
return 0;
}

转载于:https://www.cnblogs.com/tiandsp/archive/2012/02/18/2357641.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值