您的位置:首页 > 其它

算法--选择第K小的数

2014-01-10 10:26 363 查看
算法基本思想是对输入的数组进行递归划分,这样得到一个中轴元素pivot,左边数组内的数都小于等于中轴元素pivot,右边的数组都大于等于pivot,然后考察左边数组加上中轴元素的个数x,若个数x==k,则返回pivot;若x>k,则说明第K小元素在左边数组并且是第k小元素,继续递归查找;若x<k,则说明第K小元素在右边数组并且是第k-x小元素。综合上面的思想得到代码如下:

private int rand(int x,int y){
if(x>y)
return rand(y,x);
return (int)(Math.random()*(y-x)+x);
}

private int randomizedPartition(int A[],int low,int high){
int p=rand(low,high);
//exchange A[low]<->A[p]
int key=A[low];
A[low]=A[p];
A[p]=key;
//set the key value
key=A[low];
while(low<high){
while(low<high&&A[high]>=key)high--;
A[low]=A[high];
while(low<high&&A[low]<=key)low++;
A[high]=A[low];
}
A[low]=key;
return low;
}

public int randomizedSelect(int A[],int s,int t,int i){
if(s==t)
return A[s];
int p=randomizedPartition(A,s,t);
int k=p-s+1;
if(k==i)
return A[p];
else if(k>i)
return randomizedSelect(A,s,p-1,i);
else
return randomizedSelect(A,p+1,t,i-k);
}

由于C语言的随机数函数比较难用,这里用的是Java语言实现.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: