Search code examples
javascriptalgorithmsortingquicksort

quickSort algorithm errore


let quickSort = (arr) => {
    let pivot = arr[arr.length - 1];
    const rightArr = [];
    const leftArr = [];
    for(let i = 0; i < arr.length - 1 ; i++){
        if (arr[i] > pivot){
            rightArr.push(arr[i]);
        }else{
            leftArr.push(arr[i]);
        };
    };
    if (leftArr.length > 0 && rightArr.length > 0 ){
        return [...quickSort(leftArr) , pivot , ...quickSort(rightArr)];
    }else if (leftArr.length > 0){
        return [...quickSort(leftArr) , pivot]; 
        
    }else {
        return [pivot ,...quickSort(rightArr)];
    };
};
quickSort(arr);

why I had a Maximum call stack size exceeded (I still have problems with recursive functions)


Solution

  • Inside quickSort you have this code:

    if (leftArr.length > 0 && rightArr.length > 0 ){
        return [...quickSort(leftArr) , pivot , ...quickSort(rightArr)];
    }else if (leftArr.length > 0){
        return [...quickSort(leftArr) , pivot]; 
        
    }else {
        return [pivot ,...quickSort(rightArr)];
    };
    

    Which says that:

    • if it has items both to the left and the right, then sort both
    • otherwise, if it has items to the left, then sort to the left
    • otherwise sort to the right

    Your logical error is the following: you do not handle the trivial case, that is, the length of both leftArr and rightArr is not greater than 0. You would need to handle that as well

    The code below fixes one error. I do not claim that your code will work afterwards correctly, but the code below addresses the logical problem described above:

    //calculate pivot
    
    if (leftArr.length > 0 && rightArr.length > 0 ){
        return [...quickSort(leftArr) , pivot , ...quickSort(rightArr)];
    }else if (leftArr.length > 0){
        return [...quickSort(leftArr) , pivot]; 
    }else if (rightArr.length > 0){
        return [pivot ,...quickSort(rightArr)];
    }else {
        return pivot;
    };
    

    I say in a comment that you need to calculate pivot. There are multiple possible ways to do so, see https://javascript.plainenglish.io/quick-sort-algorithm-in-javascript-5cf5ab7d251b

    But first thing's first: you need to fix your stackoverflow problem first, by ensuring that in no circumstances will your function call itself infinitely many times until enough resources are wasted in order to crash the application.