【发布时间】:2014-10-15 00:10:13
【问题描述】:
我正在尝试实现一个随机选择算法,其中一个数组填充有随机数,用户选择一个位置,程序返回与数组排序版本中的位置一致的值,而不实际对数组进行排序。
问题是程序在给定位置给出元素的值,但在未排序的数组中。
import java.util.*;
public class RandomizedSelection {
public static void main(String[] args) {
int maxSize = 10; // max size of the array
int[] arr = new int[maxSize];
// fill array with random numbers between the range of 0-200
for (int i = 0; i < maxSize; i++) {
int n = (int)(java.lang.Math.random()*199);
arr[i] = n;
}
System.out.println("There is an array of 100 elements in the range" +
" of 0 - 200. Select a location to view" +
" the value.");
Scanner in = new Scanner(System.in);
int userChoice = in.nextInt(); // get user's choice of i
int loc = randomizedSelect(arr, 0, arr.length-1, userChoice);
System.out.println(loc);
System.out.println("The array was:\n" + Arrays.toString(arr));
}
public static int randomizedSelect(int[] array, int p, int r, int i) {
if (p == r)
return array[p];
if (i == 0)
return -1;
int mid = randomizedPartition(array, p, r);
int k = mid - p + 1;
if (k == i)
return array[mid];
else if (i < k)
return randomizedSelect(array, p, mid-1, i);
else
return randomizedSelect(array, mid+1, r, i-k);
}
public static int randomizedPartition(int[] array, int start, int end) {
Random rand = new Random();
int pivotIdx = rand.nextInt((end - start) + 1) + start;
int pivot = array[pivotIdx];
swap(array[pivotIdx], array[end]);
pivotIdx = end;
int i = start - 1;
for (int j = start; j <= end-1; j++) {
if (array[j] <= pivot) {
i++;
swap(array[i], array[j]);
}
}
swap(array[i+1], array[pivotIdx]);
return i+1;
}
public static void swap(int i, int j) {
int temp = i;
i = j;
j = temp;
}
}
如果用户选择位置选项 4,此程序的输出是: 50 数组为:[195, 24, 111, 50, 37, 128, 196, 117, 167, 195]
排序后的数组应该是:
[24、37、50、111、117、128、167、195、195、196]
这应该使位置选择 4 等于 111,而不是 50。
【问题讨论】:
标签: java arrays algorithm random