JS实现排序算法

曾经去面试,面试官让我写一道排序算法,结果当场没写完全,在这里补充下

  • 在这里用的方法是冒泡

  • 执行效率使用console.time(key)和console.timeEnd(key)去打印

  • 附在线示例

const arr = [9, 8, 4, 2, 5, 7, 10];
const sort = (arr, desc) => {
        const _arr = []
        for (let temp of arr) {
            if (_arr.length === 0) {
                _arr.push(temp)
            } else {
                if (temp <= _arr[0]) {
                    _arr.unshift(temp)
                } else if (temp >= _arr[_arr.length - 1]) {
                    _arr.push(temp)
                } else {
                    for (let j in _arr) {
                        if (temp > _arr[j] && temp < _arr[Number(j) + 1]) {
                            _arr.splice(Number(j) + 1, 0, temp)
                            break
                        }
                    }
                }
            }
        }
        return desc ? _arr.reverse() : _arr
}
console.time('sort')
console.log(sort(JSON.parse(JSON.stringify(arr))))
console.timeEnd('sort')
console.time('sortDesc')
console.log(sort(JSON.parse(JSON.stringify(arr)), true))
console.timeEnd('sortDesc')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值