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