我正在尝试使用快速选择来找到最接近未排序数组中位数的k个元素。我似乎无法弄清楚如何在返回的k个元素中排除中位数。有任何想法吗?这是我的代码:
public static void findClosestToMedian(int [] q, int userInput, int k) {
int mid = q.length / 2;
int median = quickSelect(q, mid, 0, q.length-1);
System.out.println("The median is: " + median);
// differences of every element from median
int [] tempDiff = new int[userInput];
int [] actualDiff = new int[userInput];
for(int i = 0; i < userInput; i++) {
tempDiff[i] = Math.abs(q[i] - median);
System.out.println(q[i] + " - " + median + " = " + tempDiff[i]);
if((tempDiff[i] + median) == q[i]) {
actualDiff[i] = tempDiff[i];
System.out.println(q[i] + " - " + median + " = " + actualDiff[i]);
} else {
actualDiff[i] = tempDiff[i] * -1;
System.out.println(q[i] + " - " + median + " = " + actualDiff[i]);
}
}
System.out.println("\nk closest");
// k closest is the k smallest difference from the median
int [] kClosest = new int[k];
for (int j = 0; j < k; j++) {
kClosest[j] = quickSelect(actualDiff, j, 0, actualDiff.length-1);
System.out.println(kClosest[j]);
}
System.out.println("");
System.out.println(k + " elements closest to the median");
// shift the found numbers back
for(int l = 0; l < k; l++) {
kClosest[l] = kClosest[l] + median;
System.out.println(kClosest[l]);
}
}