根据伪代码编程实现随机位置次序选择算法。
import java.util.Random;
public class randomizedSelection {
public static void main(String[] args){
int[] A = {
9,8,7,6,5,4,3,2,1};
//下面中randomizedSelection(A, 0, A.length-1, 5)里的第四个参数,代表的是寻找该数组中排序后的第几个元素。所以,第四个参数的值不能超过数组的长度
int result = randomizedSelection(A, 0, A.length-1, 5);
System.out.println(result);
}
//下面的代码跟快速排序的代码一样
private static int partition(int[] A, int p, int r){
int x = A[r];
int i = p-1;
for(int j = p; j<=r-1; j++){
if(A[j]<=x){
int tmp = A[i+1];
A[i+1] = A[j];
A[j] = tmp;
i++;
}
}
int t1 = A[i+1];
A[i+1] = A[r];
A[r] = t1;
return i+1;
}
//生成随机数并交换数组的最后一个值,与快速排序中的一样
private static int randomizedPartition(int[] A, int p, int r){
int random = (int) (Math.random() * ((r - p) + 1)) + p;
int temp = A[random];
A[random] = A[r];
A[r] = temp;
return partition(A, p, r);
}
//下面就是与快速排序的区别,判定大小并选择性递归
private static int randomizedSelection(int[] A, int p, int r, int k){
int q = randomizedPartition(A, p, r);
int x;
if (k==q-p+1){
x = A[q];
}else if (k<q-p+1){
x = randomizedSelection(A, p, q-1, k);
}else{
x= randomizedSelection(A, q+1, r, k-(q-p+1));
}
return x;
}
}