Search code examples
javascriptalgorithmsortingquicksort

JavaScript quickSort errore


this is the algorithme i writed

var arr = [0,2,5,10,3,22,12,8,20];


let quickSort = (arr) => {
    if(arr.length === 1){
        return arr;
    };
    let len = arr.length;

    let pivot = Math.floor(arr.length / 2);
    
    const Rightarr = [];

    const Leftarr = [];

    for(let i = 0; i < len ; i++){
        if (arr[i] < pivot){
            Leftarr.push(arr[i]);
        }else{
            Rightarr.push(arr[i]);
        };
    };
    if(Leftarr.length > 0 && Rightarr > 0){
        console.log(...quickSort(Leftarr) , pivot , ...quickSort(Rightarr));
    }else if (Leftarr.length > 0 ){
        console.log(...quickSort(Leftarr),pivot);
    }else{
        console.log(pivot,...quickSort(Rightarr));
    };
    console.log(arr);
};

quickSort(arr);

and when i run this code , i saw this in console main.js:26 Uncaught TypeError: quickSort is not iterable (cannot read property Symbol(Symbol.iterator)) at quickSort (main.js:26) at main.js:33

my question is why i get this warning , and how to fix it


Solution

  • Your quicksort function doesn't return anything as @Ivar has pointed out.

    Also, there are errors in your code

    if(Leftarr.length > 0 && Rightarr > 0)
    

    looks like it should be

    if(Leftarr.length > 0 && Rightarr.length > 0)