我创建了SortableArray类的一个实例
let test = new SortableArray([0, 50, 20, 10, 60, 30]);然后我像这样调用实例上的quickselect来找到第一个最低值,第一个最低值实际上是第二个最低值,因为它是零索引的。
test.quickselect(1, 0, test.array.length - 1);然后我没有定义,这没有任何意义,因为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];**
}
}
}发布于 2019-12-22 22:43:08
在if/else代码中调用quickselect时需要返回值,而不仅仅是在else中,如下所示
if (kthLowestValue < pivotPosition) {
return this.quickselect(kthLowestValue, leftIndex, pivotPosition - 1);
} else if (kthLowestValue > pivotPosition) {
return this.quickselect(kthLowestValue, pivotPosition + 1, rightIndex);
} else {
return this.array[pivotPosition];
}这是一个小的mocha测试文件来确认这一点:
import SortableArray from "./SortableArray";
describe('Check code', function () {
it('Run a test', function () {
let test = new SortableArray([0, 50, 20, 10, 60, 30]);
let x = test.quickselect(1, 0, test.array.length - 1);
console.log(x);
})
})新代码的结果是: 10
https://stackoverflow.com/questions/59444945
复制相似问题