随机快速排序

5 篇文章 0 订阅
2 篇文章 0 订阅

随机快速排序算法是对快速算法的一种优化,本质没什么区别,随机快速排序的最坏情况就是和快速排序一样。

上代码:

 

// Randomizde_QuickSort.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<ctime>
using namespace std;

/*函数声明*/
void Randomize_QuickSort(int *A,int p,int r);	//随机快速排序
int Randomize_Partition(int *A,int p,int r);		//随机分治法
int Partition(int *A,int p,int r);	 //分治法
void Display(int *a,int size);			//打印函数

/*主函数*/
int _tmain(int argc, _TCHAR* argv[])
{
	int size,*a;
	while(1)
	{
		cout<<"输入字符串长度:"<<endl;
		cin>>size;
		if(size > 0) {
			cout<<"请输入"<<size<<"个待排序数字:"<<endl;
			a = (int*)malloc(size*sizeof(int)); //a = new int [size];
			for(int i=0; i<size; i++)  //输入数组
			{
				cin>>a[i];
			}
			Randomize_QuickSort(a,0,size-1); //调用快速排序函数
		}
		else
			cout<<"输入长度错误!"<<endl;

		Display(a,size);   //打印数组
	}
	return 0;
}

/*函数定义*/
void Randomize_QuickSort(int *A,int p,int r)	//随机快速排序
{
	int q;
	if(p<r)               //如果p 小于等于 r 那么就程序不执行
	{
		q = Randomize_Partition(A,p,r);  //调用随机分治法 找到q的值
		Randomize_QuickSort(A,p,q-1);
		Randomize_QuickSort(A,q+1,r);
	}
}

int Randomize_Partition(int *A,int p,int r) //随机分治法
{												
	int i,temp;
	srand(time(0)); /*设置种子,并生成伪随机序列*/
	i = p+(int)((r-p+1)*rand()/(RAND_MAX+1.0));
	
	temp = A[r]; //exchange
	A[r] = A[i];
	A[i] = temp;

	return Partition(A,p,r);  //返回q值
}

int Partition(int *A,int p,int r) //分治法
{													
	int x,i,j,temp;

	x = A[r];  //将最后一个值保存在x中
	i = p-1;   //开始的时候将i 移动到数组的外面
	for( j=p; j<=r-1; j++)
	{
		if(A[j]<=x)
		{
			i +=1;
			temp = A[i]; //exchange
			A[i] = A[j];
			A[j] = temp;
		}
	}

	temp = A[i+1];  //exchange
	A[i+1] = A[r];
	A[r] = temp;

	return i+1;  //返回q值
}

void Display(int *a,int size)  //打印函数
{
	    cout<<"排序结果为:"<<endl;
		for(int i=0; i<size; i++)    //打印数组
		{
			cout<<a[i]<<" ";
		}
		cout<<endl<<endl;
}


测试结果什么的,参考我的文章,快速排序: http://blog.csdn.net/wolinxuebin/article/details/7456330
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值