Я пытаюсь найти 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]);
}
}