JS一些算法的总结

2019-02-12  本文已影响1人  supa同学

快速排序

const quickSort = (arr) => {
    const lth = arr.length;
    if (lth <= 1) {
        return arr;
    }
    const pivotIndex = Math.floor(lth / 2);
    const pivot = arr.splice(pivotIndex, 1)[0];
    const left = [];
    const right = [];
    for (let i = 0; i < arr.length; i++) {
        arr[i] < pivot ? left.push(arr[i]) : right.push(arr[i]);
    }
    return quickSort(left).concat([pivot], quickSort(right));
}
console.log(quickSort([1,2,6,3,5]));
上一篇 下一篇

猜你喜欢

热点阅读