JS sorting algorithm (a) quicksort

Ideas:

  1. Every first find that the middle value of the array as a reference
  2. It is smaller than the reference value in the array a, greater than or equal to the reference value in the other array. Note: do not talk to their reference value compared to the
  3. The two arrays to get the recursive call again. Note: Do not forget the reference value stitching in the middle, like descending na put that array is greater than the reference value at the top stitching like
var arr = [1,5,32,6,3,6,43,2];
function quickSort(arr) {
    if (arr.length <= 1) return arr;
    var leftArr = [], //这个用于存放小于基准值的数组
        rightArr = [], // 这个用于存放大于基准值的数组
        middleIndex = Math.floor(arr.length / 2),  // 找到中间的基准值的索引
        middleValue = arr.splice(middleIndex,1)[0]; //得到中间基准值,顺便把当前基准值忽略掉,避免重复比较
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] < middleValue) {
            leftArr.push(arr[i]);
        } else {
            rightArr.push(arr[i]);
        }
    }
    return quickSort(leftArr).concat(middleValue,quickSort(rightArr))
}

var res = quickSort(arr);
console.log(res); //[1, 2, 3, 5, 6, 6, 32, 43]


Guess you like

Origin www.cnblogs.com/fanzhikang/p/12549191.html