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

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






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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值