前端算法:快速排序算法

341 阅读1分钟

快速排序算法思想:

/**
    1.选择基准值base:pivotIndex:Math.floor(arr.length/2);
    2.循环原数组,小于基准值的放在left[];大于基准值的放在right[];
    3.使用递归,对left[];right[];做相同的操作;
    3.递归结束条件是arr.len<=1; return arr;
*/

talk is cheap ,show me the code:

Array.prototype.quickSort=function(arr){
    let len=arr.length;
    if(len<=1){
        return arr;
    }
    let left=[],
        right=[],
        pivotIndex=Math.floor(len/2),
        pivot=arr.splice(pivotIndex,1);
    for(let i=0;i<len;i++){
        if(arr[i]<pivot){
            left.push(arr[i]);
        }else{
            right.push(arr[i]);
        }
    }// end of for loop;    
        
    return quickSort(left).concat([pivot],quickSort(right));
}