参考: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