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

来源:互联网 发布:人均住房面积数据 编辑:程序博客网 时间:2024/04/28 13:31
#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);elsereturn 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;}


原创粉丝点击