您的位置:首页 > 编程语言 > C语言/C++

从一个数组中找出第k小元素的随机化算法 c语言实现 算法导论第九章

2013-08-05 21:45 351 查看
//Randomized_select,select a particular number from an array in linear time
#include <stdio.h>
#include <stdlib.h>
void swap(int *p,int *q)//交换元素
{
int temp;
temp=*p;
*p=*q;
*q=temp;
}
int Random(int p,int r)//产生p与r之间的一个随机数
{
int result=p+rand()%(r-p+1);
return result;
}
int partition(int A[],int p,int q)//划分
{
int j=p,i=j-1;
int r=A[q];
for(int k=p;k<q;k++)
{
if(A[k]<=r)
{
i=i+1;
swap(&A[i],&A[k]);
}
}
swap(&A[i+1],&A[q]);
return i+1;
}
int Randomized_partition(int A[],int p,int r)//随机划分过程
{
int i=Random(p,r);
swap(&A[i],&A[r]);
return partition(A,p,r);
}

int Random_select(int A[],int p,int r,int i)//select the ith element
{
if(p==r)
return A[p];//If there is only one array,then just return the only element
int q,k;
q=Randomized_partition(A,p,r);//the partition of the array
k=q-p+1;//the location of A[q]
if(i==k)//k is the right place
return A[q];
else
if(i<k)
return Random_select(A,p,q-1,i);
else
return Random_select(A,q+1,r,i-k);
}

void main()
{
int A[]={0,4,3,5,6,1,8,9};
int x=Random_select(A,1,7,6);
printf("the 2th number is %d\n",x);
}






                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: