# 合并二维有序数组成一维有序数组,归并排序的思路
# 昨日回顾
自己做定时器,间隔时间是 a, a+b a+2b...a+nb
function myIntervalFn(fn, a, b) {
this.a = a;
this.b = b;
this.time = 0;
this.timer = null;
this.start = () => {
this.timer = setTimeout(() => {
fn();
this.start();
this.time++;
}, a + this.time * this.b);
};
this.stop = function() {
if (this.timer) {
clearTimeout(this.timer);
this.time = 0;
}
};
}
function aa() {
console.log(111);
}
const a = new myIntervalFn(aa, 1000, 2000);
a.start();
setTimeout(function() {
a.stop();
}, 10000);
# 今日份解题
const soucreArr = [
[1, 21, 123, 12],
[11, 23, 12, 123],
[543, 652, 5, 7, 78],
];
/// 方法一: flat
function myFlatSort(arr) {
return [...new Set(soucreArr.flat(Infinity).sort((a, b) => a - b))];
}
/// 方法二: concat
function myConncat(arr) {
let copyArr = [...arr];
while (copyArr.some((item) => Array.isArray(item))) {
copyArr = [].concat(...copyArr);
console.log(copyArr);
}
return copyArr;
}
/// 方法三:reduce
function myReduce(arr) {
const arrCopy = arr.reduce((acc, cur) => {
return Array.isArray(cur) ? [...acc, ...myReduce(cur)] : [...acc, cur];
}, []);
return arrCopy;
}
/// 方法四:
// 排序一个数组,先把数组从中间分成前后两部分,然后对前后两部分分别排序,再将排序好的两部分合并到一起,这样整个数组就有序了
/// 归并排序采用的是分治思想
function mergeSort(arr) {
const len = arr.length;
if (len < 2) return arr;
const middleIndex = len >> 1;
const left = arr.slice(0, middleIndex);
const right = arr.slice(middleIndex);
return merge(mergeSort(left), mergeSort(right));
}
function merge(left, right) {
const result = [];
while (left.length && right.length) {
if (left[0] <= right[0]) {
/// 类似队列的队首出队
result.push(left.shift());
} else {
result.push(right.shift());
}
}
/// 如果还有剩余元素,直接从头到尾放到数组尾部
while (left.length) result.push(left.shift());
while (right.length) result.push(right.shift());
return result;
}
function flatten(arr) {
return arr.reduce((pre, cur) => {
return pre.concat(Array.isArray(cur) ? flatten(cur) : cur);
}, []);
}
mergeSort(flatten(soucreArr));