我创建了一个SortableArray
类的实例
let test = new SortableArray([0, 50, 20, 10, 60, 30]);
然后我像这样调用quickselect
实例来找到第一个最低值,第一个最低值实际上是第二低的值,因为它是零索引的。
test.quickselect(1, 0, test.array.length - 1);
然后我得到 undefined,这没有任何意义,因为 quickselect 方法包含一个 return 语句。
class SortableArray{
constructor(array){
this.array = array;
}
swap(pointer1, pointer2){
let temporary = this.array[pointer1];
this.array[pointer1] = this.array[pointer2];
this.array[pointer2] = temporary
}
partition(leftPointer, rightPointer) {
let count = 0;
let temporary;
let pivotPosition = rightPointer;
let pivot = this.array[pivotPosition];
rightPointer -= 1;
do{
while((this.array[leftPointer] < pivot) && (leftPointer <= rightPointer)){
leftPointer++;
}
while((this.array[rightPointer] > pivot) && (leftPointer <= rightPointer)){
rightPointer--;
}
if((leftPointer <= rightPointer)){
this.swap(leftPointer,rightPointer);
continue;
}
break;
}while((leftPointer !== rightPointer) && (leftPointer <= rightPointer));
this.swap(leftPointer, pivotPosition);
return leftPointer;
}
quickselect(kthLowestValue, leftIndex, rightIndex){
debugger;
if(rightIndex - leftIndex <= 0){
return this.array[leftIndex];
}
let pivotPosition = this.partition(leftIndex, rightIndex);
if(kthLowestValue < pivotPosition){
this.quickselect(kthLowestValue, leftIndex, pivotPosition - 1);
}else if(kthLowestValue > pivotPosition){
this.quickselect(kthLowestValue, pivotPosition + 1, rightIndex);
}else{
**return this.array[pivotPosition];**
}
}
}