首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >下面的quickselect方法在我调用它时返回undefined。它是不是跟quickselect自称为的东西有关?

下面的quickselect方法在我调用它时返回undefined。它是不是跟quickselect自称为的东西有关?
EN

Stack Overflow用户
提问于 2019-12-22 22:11:30
回答 1查看 25关注 0票数 0

我创建了SortableArray类的一个实例

代码语言:javascript
复制
let test = new SortableArray([0, 50, 20, 10, 60, 30]);

然后我像这样调用实例上的quickselect来找到第一个最低值,第一个最低值实际上是第二个最低值,因为它是零索引的。

代码语言:javascript
复制
test.quickselect(1, 0, test.array.length - 1);

然后我没有定义,这没有任何意义,因为quickselect方法包含一条return语句。

代码语言:javascript
复制
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];**
    }
  }
}
EN

回答 1

Stack Overflow用户

发布于 2019-12-22 22:43:08

if/else代码中调用quickselect时需要返回值,而不仅仅是在else中,如下所示

代码语言:javascript
复制
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测试文件来确认这一点:

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59444945

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档