package chap09_Medians_and_Order_Statistics;
import static org.junit.Assert.*;
import java.util.Random;
import org.junit.Test;
public class SearchAlorithms {
/**
* 分割(快速排序中对数组的分割)
*
* @param n
* @param start
* @param end
* @return
*/
protected static int partition(int[] n, int start, int end) {
int p = end - 1;
int s = start;// s位于大于a[p]和小于a[p]之间的位置
int tmp;
for (int i = start; i < end; i++) {
if (n[i] < n[p]) {
tmp = n[i];
n[i] = n[s];
n[s] = tmp;
s++;
}
}
{
tmp = n[s];
n[s] = n[p];
n[p] = tmp;
}
return s;
}
/**
* 随机分割,将一个数组从随机选择的位置处分割,左边小,右边大
*
* @param n
* @param start
* @param end
* @return
*/
static protected int randomPartition(int[] n, int start, int end) {
Random rand = new Random(23);
int t = rand.nextInt(end - start) + start;
int tmp;
{
tmp = n[t];
n[t] = n[end - 1];
n[end - 1] = tmp;
}
return partition(n, start, end);
}
/**
* 搜索数组n中从start到end之间第k小的数字
*
* @param n
* @param start
* @param end
* @param k
* @return
*/
static int randomSearch(int[] n, int start, int end, int k) {
if (start == end - 1)
return n[start];
int q = randomPartition(n, start, end);
int p = q - start + 1;
if (k == p)
return n[q+1];
else if (k > p)
return randomSearch(n, q, end, k - q);
else
return randomSearch(n, start, q, k);
}
@Test
public void testName() throws Exception {
int[] n = { 13, 19, 9, 5, 12, 8, 7, 4, 21, 2, 6, 11 };
int a = randomSearch(n, 0, 12, 1);
System.out.println(a);
}
}