js 快速排序

前端工作中常用到的算法之一:快速排序法

直接上代码

this.textFun()
methods: {
            textFun() {
                const arr = [1,2,8,5,3,2,0]
                const initArr = this.sortArr(arr)
                console.log(initArr)
            },
            sortArr(arr) {
                if (arr.length <= 1) {
                    return arr
                }
                const left = [], right = [], current = arr.splice(0, 1);
                for (let i = 0; i < arr.length; i++) {
                    if (arr[i] < current) {
                        left.push(arr[i])
                    } else {
                        right.push(arr[i])
                    }
                }
                return this.sortArr(left).concat(current, this.sortArr(right))
            },
}

你可能感兴趣的:(js 快速排序)