0

I create an instance of the SortableArray class

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

I then call quickselect on the instance like so to find the 1st lowest value, The 1st lowest value is actually the second-lowest value since it is zero-indexed.

test.quickselect(1, 0, test.array.length - 1);

I then get undefined, which doesn't make any sense since the quickselect method contains a return statement.

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];**
    }
  }
}
Tamir Klein
  • 3,514
  • 1
  • 20
  • 38
joembarron
  • 141
  • 7

1 Answers1

0

You need to return the values when calling quickselect in your if/else code and not only in the else like this

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

This is a small mocha test file to confirm this:

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);
    })

})

The result of the new code is: 10

Tamir Klein
  • 3,514
  • 1
  • 20
  • 38