4.quickSort - Javascript

less than 1 minute read

4.quickSort - Javascript


const arr = [3,2,1,4]

function quickSort(items){
    return quickSortHelper(items,0,items.length-1)
}

function quickSortHelper(items,left,right) {
    var index;
    if( items.length > 1 ){
        index = partition(items,left,right);
        if(left < index -1){
            quickSortHelper(items,left,index-1);
        }
        if(left < right){
            quickSortHelper(items,index,right);
        }
    }
    return items;
}

function partition(array,left,right){
    var pivot = array[ Math.floor( (right+left)/2 ) ];
    while( left <= right ){
        while( pivot > array[left]){
            left++;
        }
        while( pivot < array[right]){
            right--;
        }
        if( left <= right ){
            var temp = array[left];
            array[left] = array[right];
            array[right] = temp;
            left++;
            right--;
        }
    }
    return left;
}


quickSort(arr)
console.log(arr)





Leave a comment