递归分治解决快速排序和限行时间选择

#include<iostream>
using namespace std;
#include<time.h>
#include<stdlib.h>
#define Random(x) (rand()%x)

template<class Type>
void Swap(Type &m,Type &n){//交换两个数
	Type temp = m;
	m = n;
	n = temp;
}

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>
int RandomizedPartition(Type a[],int p,int r){
	srand((int)time(0));
	
	int i = p + rand()%(r-p);
	
	Swap(a[i],a[p]);
	return Partition(a,p,r);
}

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);
	}
}

void Output(int a[],int n){
	for(int i = 0;i < n;i++)
		cout<<a[i]<<" ";
}

template<class Type>
Type RandomizedSelect(Type a[],int p,int r,int k){
	if(p == r)
		return a[p];
	int i = RandomizedPartition(a,p,r),
		j = i - p + 1;
	if(k <= j)
		return RandomizedSelect(a,p,i,k);
	else
		return RandomizedSelect(a,i+1,r,k-j);
}

void main(){
	
	int k;
	int a[7] = {49,38,65,97,76,13,27};
	cout<<"数组如下"<<endl;
	Output(a,7);
	RandomizedQuickSort(a,0,6);
	cout<<"\n排序后数组元素如下"<<endl;
	Output(a,7);
	cout<<endl<<"输入k(0<k<8):";
	cin>>k;
	cout<<"第"<<k<<"小的数为"<<endl;
	cout<<RandomizedSelect(a,0,6,k);
	cout<<endl;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值