, . , , , , -
"sort merge" . , 1950 , , , .
https://en.wikipedia.org/wiki/Merge_algorithm. JS . N-way. . , , , .
- . "------" , , , , . -, "-" " ".
JS
, , , :
const data = [[1, 3, 5], [2, 4]];
function merge(arrays, sortFunc) {
let result = [], next;
arrays.forEach(array => array.index = 0);
function findNext() {
return arrays.filter(array => array.index < array.length)
.sort((a, b) => sortFunc(a[a.index], b[b.index]))[0];
}
while (next = findNext()) result.push(next[next.index++]);
return result;
}
function arithAscending(a, b) { return a - b; }
console.log(merge(data, arithAscending));
Hide resultindex , , . shift , , .
findNext, , . , "min-heap" , . - , , node , , () .. JS - .
, , , .
const data = [[1, 3, 5], [2, 4]];
function* merge(iterables, sortFunc) {
let next;
const iterators = iterables.map(iterable => {
const iterator = iterable[Symbol.iterator]();
iterator.result = iterator.next();
return iterator;
});
function findNext() {
return iterators
.filter(iterator => !iterator.result.done)
.reduce((ret, cur) => !ret || cur.result.value < ret.result.value ? cur : ret,
null);
}
while (next = findNext()) {
yield next.result.value;
next.result = next.next();
}
}
function arithAscending(a, b) { return a - b; }
console.log(Array.from(merge(data, arithAscending)));
Hide resultuser663031