0

why is this function throwing error

I am trying to sort array using quickSort with a recursion approach here I am using the last element in the array as a pivot

let array = [1,0,123,1,3,12,2,45,6]
function quickSort(array, leastIndex, highIndex) {
    if (leastIndex >= highIndex) return;

    const pivot = array[highIndex];
    let leftPointer = leastIndex;
    let rightPointer = highIndex;

    while (leftPointer < rightPointer) {
        while (array[leftPointer] <= pivot && leftPointer < rightPointer) {
            leftPointer++;
        }
        while (array[rightPointer] >= pivot && rightPointer > leftPointer) {
            rightPointer--;
        }
        swap(array, leftPointer, rightPointer)
    }
    swap(array, leftPointer, highIndex);
    quickSort(array, leastIndex, leftPointer);
    quickSort(array, leftPointer + 1, highIndex);
}

function swap(array, a, b) {
    let temp = array[a]
    array[a] = array[b]
    array[b] = temp
}
quickSort(array,0,array.length-1)
console.log(array);

ERROR

Uncaught RangeError: Maximum call stack size exceeded
    at swap (<anonymous>:23:14)
    at quickSort (<anonymous>:16:9)
    at quickSort (<anonymous>:19:5)
    at quickSort (<anonymous>:19:5)
    at quickSort (<anonymous>:19:5)
    at quickSort (<anonymous>:19:5)
    at quickSort (<anonymous>:19:5)
    at quickSort (<anonymous>:19:5)
    at quickSort (<anonymous>:19:5)
    at quickSort (<anonymous>:19:5)
7
  • Please add the error to the question so other members can help you. Commented Aug 5, 2022 at 14:25
  • You want the solution with the proper answer on how to do it or us to fix this one? Commented Aug 5, 2022 at 14:32
  • Fix this one, please Commented Aug 5, 2022 at 14:33
  • In that way you have a Stack Overflow ;p which means that your stopping point never happens and it keeps running. Commented Aug 5, 2022 at 14:33
  • I am not able to figure out what is causing the error Commented Aug 5, 2022 at 14:35

2 Answers 2

1

The problem is that when the pivot is also the greatest value, that the first recursive call will be made with exactly the same range again, and so the partition to sort isn't becoming smaller...

Since your version of Quicksort ensures that you have the index of the pivot value (after the final swap), you can exclude that value from further recursive calls. So change:

quickSort(array, leastIndex, leftPointer);

to:

quickSort(array, leastIndex, leftPointer - 1);
Sign up to request clarification or add additional context in comments.

Comments

0

The problem is in this line

quickSort(array, leastIndex, leftPointer);

It should be

quickSort(array, leastIndex, leftPointer - 1);

Comments

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.