Вот мой код:
public static <T> T partition(int k, T[] arr, Comparator<T> comparator, Random rand, int low, int high) {
if (low >= high) {
return arr[low];
}
int pivotIndex = rand.nextInt(high - low) + low;
int i = low - 1;
for (int j = low; j < high; j++) {
if (comparator.compare(arr[j], arr[pivotIndex]) < 0) {
i++;
if (i == pivotIndex) {
pivotIndex = j;
}
swap(arr, i, j);
}
}
swap(arr, i + 1, pivotIndex);
pivotIndex = i + 1;
if (pivotIndex + 1 == k) {
return arr[pivotIndex];
} else if (pivotIndex + 1 < k) {
return partition(k - pivotIndex + 1, arr, comparator, rand, pivotIndex + 1, high);
} else {
return partition(k, arr, comparator, rand, low, pivotIndex);
}
}