下面是我试图理解中位数算法中位数的代码(使用大小为 5 的块)。我了解如何获得输入的中位数,但我不确定如何对块进行编码以继续递归输入,直到我只有中位数。然后在得到那个中值之后,我不知道如何用它作为一个支点来丢弃无用的信息来划分输入。getMediansArray
返回大小为 ceil(input.length/5) 的数组,并getMedians
仅返回数组的中位数(仅用于长度 <= 5 的数组)。
public static int[] findKthElement(int[] input, int k) {
int numOfMedians = (int) Math.ceil(input.length/5.0);
int[] medians = new int[numOfMedians];
medians = getMediansArray(input, medians)
// (1) This only gets the first iteration of medians of the
// input. How do I recurse on this until I just have one median?
// (2) how should I partition about the pivot once I get it?
}
public static int[] getMediansArray(int[] input, int[] medians) {
int numOfMedians = (int) Math.ceil(input.length/5.0);
int[] five = new int[5];
for (int i = 0; i < numOfMedians; i++) {
if (i != numOfMedians - 1) {
for (int j = 0; j < 5; j++) {
five[j] = input[(i*5)+j];
}
medians[i] = getMedian(five);
} else {
int numOfRemainders = input.length % 5;
int[] remainder = new int[numOfRemainders];
for (int j = 0; j < numOfRemainders; j++) {
remainder[j] = input[(i*5)+j];
}
medians[i] = getMedian(five);
}
}
return medians;
}
public static int getMedian(int[] input) {
Arrays.sort(input);
if (input.length % 2 == 0) {
return (input[input.length/2] + input[input.length/2 - 1]) / 2;
}
return input[input.length/2];
}