JS实现数组快速排序

121 篇文章 3 订阅

参考:http://www.ruanyifeng.com/blog/2011/04/quicksort_in_javascript.html

快速排序法

const log = console.log;
function rand(min, max) {
    let f = Math.min(min, max);
    let t = Math.max(min, max);
    let len = Math.abs(t - f);
    let r = Math.floor(f + Math.random() * len);
    return r;
}

log("random ", rand(7, 292));

let arr = [
    56, 5, 15, 81, 29,
    59, 59, 79, 8
];

function quick(arr1) {
    if (arr1.length <= 1) {
        return arr1;
    }

    let mIndex = Math.floor(arr1.length / 2);
    let mV = arr1.splice(mIndex, 1)[0];
    let left = [];
    let right = [];

    for (let i = 0; i < arr1.length; i++) {
        if (arr1[i] < mV) {
            left.push(arr1[i]);
        } else {
            right.push(arr1[i]);
        }
    }

    return quick(left).concat(mV, quick(right));
}

log(arr)
log(quick(arr))

let b = [7, 9, 4];
let c = b.concat(1, 2, [78, 92]);//concat中参数是数组的,会将数组自动拆分成多个逗号连接
log(c)
log(b)
log("end")

大数组排序时,节约点内存。arr.concat()连接时,如果参数是数组,会自动将数组展开

const log = console.log;
function rand(min, max) {
    let f = Math.min(min, max);
    let t = Math.max(min, max);
    let len = Math.abs(t - f);
    let r = Math.floor(f + Math.random() * len);
    return r;
}

log("random ", rand(7, 292));

let arr = [
    56, 5, 15, 81, 29,
    59, 59, 79, 8
];

function quick(arr1) {
    if (arr1.length <= 1) {
        return arr1;
    }

    let mIndex = Math.floor(arr1.length / 2);
    let mV = arr1.splice(mIndex, 1)[0];
    let left = [];
    let right = [];

    for (let i = arr1.length-1; i >= 0; i--) {
        // let v = arr1.splice(i,1)[0];
        let v = arr1.pop();//大数组排序时节约点内存。
        if (v < mV) {
            left.push(v);
        } else {
            right.push(v);
        }
    }

    return quick(left).concat(mV, ...quick(right));
}

log(arr)
log(quick(arr))

// let b = [7, 9, 4];
// let c = b.concat(1, 2, ...[78, 92]);//concat中参数是数组的,会将数组自动拆分成多个逗号连接
// log(c)
// log(b)
log("end")

结果:

PS E:\study\js\two\src> node .\testjs.js
random  101
[
  56,  5, 15, 81, 29,
  59, 59, 79,  8
]
[
   5,  8, 15, 29, 56,
  59, 59, 79, 81
]
end

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值