插入排序

非原地:

const arr = [3, 4, 2, 7, 9, 6, 2, 8, 3, 6, 2, 1, 6, 3, 7, 4, 21, 8, 0, 5];
// const arr = [3, 4, 2];

function bubble(data) {
    var cache = [];
    var num;
    while (data.length > 0) {
        num = data.pop();
        cacheInOrder(num);
    }
    return cache;

    function cacheInOrder(n) {
        if (cache.length === 0) {
            cache.push(n);
            return;
        }
        for (var i = 0; i < cache.length; i++) {
            if (n <= cache[i]) {
                cache.splice(i, 0, n);
                break;
            }
            if (i == cache.length - 1) {
                cache.push(n);
                break;
            }
        }
    }
}

console.time('计时');
bubble(arr);
console.timeEnd('计时');

 

posted @ 2020-09-11 22:47  潴哥  阅读(132)  评论(0编辑  收藏  举报