我做了快速选择算法,就是在一个数组中找到第k个最小的数。我的问题是,它只适用于没有重复的数组。如果我有一个数组
arr = {1,2,2,3,5,5,8,2,4,8,8}
它会说第三小的数字是 2,但实际上是 3。
我被困在做什么,这是我的两个方法 quickSelect 和 Partition:
private int quickselect(int[] array, int leftIndex, int rightIndex, int kthSmallest) {
if(kthSmallest > array.length - 1){
System.out.print("Number does not exist. Please enter a number less than: ");
return array.length - 1;
}
if (leftIndex == rightIndex) {
return array[leftIndex];
}
int indexOfPivot = generatePivot(leftIndex, rightIndex);
indexOfPivot = quickSelectPartition(array, leftIndex, rightIndex, indexOfPivot);
if (kthSmallest == indexOfPivot) {
return array[kthSmallest];
} else if (kthSmallest < indexOfPivot) {
return quickselect(array, leftIndex, indexOfPivot - 1, kthSmallest);
} else {
return quickselect(array, indexOfPivot + 1, rightIndex, kthSmallest);
}
}
private int quickSelectPartition(int[] array, int left, int right, int pivotIndex) {
int pivotValue = array[pivotIndex];
swapIndexes(array, pivotIndex, right);
int firstPointer = left;
for(int secondPointer = left; secondPointer < right; secondPointer++) {
if(array[secondPointer] < pivotValue) {
swapIndexes(array, firstPointer, secondPointer);
firstPointer++;
}
}
swapIndexes(array, right, firstPointer);
return firstPointer;
}
慕神8447489
相关分类