0

SortableArrayクラスのインスタンスを作成します

let test = new SortableArray([0, 50, 20, 10, 60, 30]);

次に、そのようにインスタンスを呼び出しquickselectて、1 番目に低い値を見つけます。1 番目に低い値は、インデックスがゼロであるため、実際には 2 番目に低い値です。

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];**
    }
  }
}
4

1 に答える 1