0

I'm trying to implement the quicksort algorithm using recursion in Javascript and while I'm return when I meet the base case it's not happening. Please help me. Following is the code I've written.

function randomArray(){
  let array = [];
  let length = Math.floor(Math.random()*22);
  for(let i=0;i<length;i++){
    array.push(Math.floor(Math.random()*50));
  }
  return array;
} // IT RETURNS THE RANDOM ARRAY WITH RANDOM SERIES OF NUMBERS;


function swapper(array, indexNumber, bigNumber){
  let temp = array[bigNumber];
  if(bigNumber-indexNumber>1){
    array[bigNumber]=array[indexNumber+1];
    array[indexNumber+1]=array[indexNumber];
    array[indexNumber]=temp;
    indexNumber =  indexNumber+1;
  }else{
    array[bigNumber]=array[indexNumber];
    array[indexNumber]=temp;
    indexNumber = bigNumber;
  }
} // HELPER FUNCTION WHICH HELPS TO PUT THE ELEMENT IN CORRECT PLACE

let hull =0;

function quickSort(array, index, object, length){ //MAIN FUNCTION 
  
  if(object[index]!==undefined){
    hull++;
    if(hull<array.length){
    quickSort(array,hull, object,length);
    }else{
      console.log(array, "from the heaven", hull); //CONSOLES AFTER HULL IS GREATER THAN OR EQUAL TO LENGTH OF ARRAY BUT STILL CONSOLING EVEN IT'S GREATER THAN ARRAY'S LENGTH
      return array;
    }
    
  }else{
    for(let i=index+1;i<array.length;i++){
      if(array[i]<array[index]){
        swapper(array, index, i);
        index = index+1;
      }
    }
    object[index]=true;
  }
  quickSort(oneArray, hull, object, length);
}
console.log(quickSort(randomArray(),0,{},0));

I tried the base case, the code should return when the variable hull is greater than length of an array but the code running even after the hull increments length of an array. I don't know what's happening there please explain

3
  • 1
    This question is similar to: How to implement a stable QuickSort algorithm in JavaScript. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Sep 23, 2024 at 20:39
  • 1
    The call quickSort(oneArray, hull, object, length) should be quickSort(array, hull, object, length)? Commented Sep 23, 2024 at 20:49
  • @PM77-1, that question is specifically about a stable implementation of quicksort, not the inplace way to implement quicksort, which is what is attempted here. Commented Sep 24, 2024 at 9:53

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.