javascriptquicksort

I am getting a "Maximum call stack size exceeded" error in a JS code and I can't figure out why. Can someone help me with it?


I was trying to write a quick sorting algorithm in JS when this error occured.

const x = [10, 9, 20, 3, 2, 4, 50, 69, 11, 5];

function partion(array){
    let pivot = array.length - 1;
    let tem_storage = 0;
    let i = -1;
    for (let j = 0; j <= x.length - 1; j+=1){
        if (array[j] < array[pivot]){
            tem_storage = array[j];
            i += 1;
            array[j] = array[i];
            array[i] = tem_storage;
        }
        else if (array[i] > array[pivot]){
            j += 1;
        }

    }
    i += 1;
    tem_storage = array[i];
    array[i] = array[pivot];
    array[pivot] = tem_storage;
    return i;
}

function quick_sort(array, low, high){
    if(low < high){
        let pi = partion(array);
        quick_sort(array, low, pi - 1);
        quick_sort(array, pi + 1, high);
    }
}

quick_sort(x, 0, x.length);

console.log(x);

In the quick_sort function the quick_sort(array, low, pi - 1); is causing the error.

I deleted that line of code and the program seemed to work. I am relatively new to programming and algorithms. I don't know why its causing the error but can someone explain.


Solution

  • You are having a problem with infinite recursion.

    Please check this

    function partition(array, low, high) {
        let pivot = array[high];
        let i = low - 1;
    
        for (let j = low; j < high; j++) {
            if (array[j] < pivot) {
                i++;
                [array[i], array[j]] = [array[j], array[i]]; // Swap elements
            }
        }
    
        [array[i + 1], array[high]] = [array[high], array[i + 1]]; // Swap the pivot
        return i + 1;
    }
    
    function quick_sort(array, low, high) {
        if (low < high) {
            let pi = partition(array, low, high);
            quick_sort(array, low, pi - 1);
            quick_sort(array, pi + 1, high);
        }
    }