快速排序(ES6)
function qSort (arr) { if (arr.length <= 1) { return arr } const mVal = arr.shift() // 这是基准数,比这小的放左边数组, 比这大的放在右边 let [left, right] = [[], []] arr.forEach(item => item < mVal ? left.push(item) : right.push(item)) return [...qSort(left), mVal, ...qSort(right)] }
快速排序(ES6)改进: 增加参数解构
function qSort ([x0, ...xn]) { return typeof x0 === 'number' ? [...qSort(xn.filter(item => item < x0)), x0, ...qSort(xn.filter(item => item >= x0))] : [] }
测试:
const arr = [1, 12, 22, 82, 4, 7, 0, 25, 3, 71, 9, 44, 8, 9, 112] const BiggerQsort = qSort((a, b) => a < b) const SmallerQsort = qSort((a, b) => a > b) console.log(BiggerQsort(arr)) // [0, 1, 3, 4, 7, 8, 9, 9, 12, 22, 25, 44, 71, 82, 112] console.log(SmallerQsort(arr)) // [112, 82, 71, 44, 25, 22, 12, 9, 9, 8, 7, 4, 3, 1, 0]