/** * Introduction to Algorithms, Second Edition * 9.2 RANDOMIZED-SELECT * @author 土豆爸爸 * */ public class RandomizedSelect { /** * 选择数组从p到r之间,第i个最小值。 * @param array 数组 * @param p 起始索引 * @param r 结束索引 * @param i 最小值索引 * @return 从p到r之间,第i个最小值 */ public static int select(int[] array, int p, int r, int i) { if(p == r) { return array[p]; } int q = RandomizedQuickSort.randomizedPartition(array, p, r); int k = q - p + 1; if(k == i) {//支点是答案 return array[q]; } else if(i < k) { //从前半部分找 return select(array, p, q-1, i); } else { //从后半部分找,且位置为i-k return select(array, q+1, r, i-k); } } } import junit.framework.TestCase; public class RandomizedSelectTest extends TestCase { public void testFixArray() { int[] array = { 5, 2, 4, 6, 1, 3 }; assertEquals(1, RandomizedSelect.select(array, 0, array.length - 1, 1)); assertEquals(3, RandomizedSelect.select(array, 0, array.length - 1, 3)); } public void testRandomArray() { int size = (int)(Math.random()* 1000) + 4; int[] array = new int[size]; for(int i = 0; i < size; i++) { array[i] = (int)(Math.random()* 10000); } int[] clone = array.clone(); RandomizedQuickSort.sort(clone, 0, array.length - 1); assertEquals(clone[0], RandomizedSelect.select(array, 0, array.length - 1, 1)); assertEquals(clone[size - 1], RandomizedSelect.select(array, 0, array.length - 1, size)); int random = (int)(Math.random()* size); assertEquals(clone[random], RandomizedSelect.select(array, 0, array.length - 1, random + 1)); } }
算法导论示例-RandomizedSelect
最新推荐文章于 2021-11-12 16:14:15 发布