Algorithm for combining multiple sorted sequences into one sorted sequence in javascript

enter image description here I am looking for an algorithm to combine several sorted sequences, say, X sorted sequences with n elements, into one sorted sequence in javascript, can you give some examples?

note: I do not want to use any library. Trying to resolve https://icpc.kattis.com/problems/stacking

what is the minimum number of operations required to merge sorted arrays, under the conditions:

Split : one stack can be split into two stacks by lifting any top of the stack and setting it aside to form a new stack.

: , . , , .. .

+4
6

k . n, O(k*n*log(k*n)). !

. :

var sorted = [];
var pq = new MinPriorityQueue(function(a, b) {
  return a.number < b.number;
});
var indices = new Array(k).fill(0);
for (var i=0; i<k; ++i) if (sequences[i].length > 0) {
  pq.insert({number: sequences[i][0], sequence: i});
}
while (!pq.empty()) {
  var min = pq.findAndDeleteMin();
  sorted.push(min.number);
  ++indices[min.sequence];
  if (indices[min.sequence] < sequences[i].length) pq.insert({
    number: sequences[i][indices[min.sequence]],
    sequence: min.sequence
  });
}

k , . .

:

  • k*n k: O(k*n)
  • k*n k: O(k*n*log(k))
  • : O(k*n)

O(k*n*log(k))

+6

, . , , , , - "sort merge" . , 1950 , , , .

https://en.wikipedia.org/wiki/Merge_algorithm. JS . N-way. . , , , .

- . "------" , , , , . -, "-" " ".

JS

, , , :

const data = [[1, 3, 5], [2, 4]];    

// Merge an array or pre-sorted arrays, based on the given sort criteria.
function merge(arrays, sortFunc) {
  let result = [], next;
   
  // Add an 'index' property to each array to keep track of where we are in it.
  arrays.forEach(array => array.index = 0);
 
  // Find the next array to pull from.
  // Just sort the list of arrays by their current value and take the first one.     
  function findNext() {
    return arrays.filter(array => array.index < array.length)
      .sort((a, b) => sortFunc(a[a.index], b[b.index]))[0];
  }

  // This is the heart of the algorithm.
  while (next = findNext()) result.push(next[next.index++]);

  return result;
}

function arithAscending(a, b) { return a - b; }

console.log(merge(data, arithAscending));
Hide result

index , , . shift , , .

findNext, , . , "min-heap" , . - , , node , , () .. JS - .

, , , .

// Test data.
const data = [[1, 3, 5], [2, 4]];

// Merge an array or pre-sorted arrays, based on the given sort criteria.
function* merge(iterables, sortFunc) {
  let next;

  // Create iterators, with "result" property to hold most recent result.
  const iterators = iterables.map(iterable => {
    const iterator = iterable[Symbol.iterator]();
    iterator.result = iterator.next();
    return iterator;
  });

  // Find the next iterator whose value to use.
  function findNext() {
    return iterators
      .filter(iterator => !iterator.result.done)
      .reduce((ret, cur) => !ret || cur.result.value < ret.result.value ? cur : ret, 
         null);
  }

  // This is the heart of the algorithm.
  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 result
+5

es6:

function mergeAndSort(arrays) {
    return [].concat(...arrays).sort()
}

.

* : @Redu, . sort() , Unicode. ( ) :

function mergeAndSort(arrays) {
    return [].concat(...arrays).sort((a,b)=>a-b)
}
+1

.

, , ( ), , .

.

0

. .sort(); .reduce() O (m.n). m - , n - .

. , ..

function mergeSortedArrays(a){
  return a.reduce(function(p,c){
                    var pc = 0,
                        cc = 0,
                       len = p.length < c.length ? p.length : c.length,
                       res = [];
                    while (p[pc] !== undefined && c[cc] !== undefined) p[pc] < c[cc] ? res.push(p[pc++])
                                                                                     : res.push(c[cc++]);
                    return p[pc] === undefined ? res.concat(c.slice(cc))
                                               : res.concat(p.slice(pc));
                  });
}


var sortedArrays = Array(5).fill().map(_ => Array(~~(Math.random()*5)+5).fill().map(_ => ~~(Math.random()*20)).sort((a,b) => a-b));
 sortedComposite = mergeSortedArrays(sortedArrays);

sortedArrays.forEach(a => console.log(JSON.stringify(a)));
console.log(JSON.stringify(sortedComposite));
Hide result

@Mirko Vukušić .concat() .sort(), - FF, Chrome. Chrome.sort() , . JS, . , FF concat sort.

function mergeSortedArrays(a){
  return a.reduce(function(p,c){
                    var pc = 0,
                        pl =p.length,
                        cc = 0,
                        cl = c.length,
                       res = [];
                    while (pc < pl && cc < cl) p[pc] < c[cc] ? res.push(p[pc++])
                                                             : res.push(c[cc++]);
                    if (cc < cl) while (cc < cl) res.push(c[cc++]);
                    else while (pc < pl) res.push(p[pc++]);
                    return res;
                  });
}

function concatAndSort(a){
  return a.reduce((p,c) => p.concat(c))
          .sort((a,b) => a-b);
}


var sortedArrays = Array(5000).fill().map(_ => Array(~~(Math.random()*5)+5).fill().map(_ => ~~(Math.random()*20)).sort((a,b) => a-b));
console.time("merge");
 mergeSorted = mergeSortedArrays(sortedArrays);
console.timeEnd("merge");
console.time("concat");
concatSorted = concatAndSort(sortedArrays);
console.timeEnd("concat");
Hide result

5000 5-10.

0

javascript-, . , . . . , . , . . , . , , , .

function merge() {
   var mergedArr = [],pos = [], finished = 0;
   for(var i=0; i<arguments.length; i++) {
       pos[i] = 0;
   }
   while(finished != arguments.length) {
       var min = null, selected;
       for(var i=0; i<arguments.length; i++) {
          if(pos[i] != arguments[i].length) {
              if(min == null || min > arguments[i][pos[i]]) {
                  min = arguments[i][pos[i]];
                  selected = i;
              }
          }
      }
      mergedArr.push(arguments[selected][pos[selected]]);
      pos[selected]++;
      if(pos[selected] == arguments[selected].length) {
         finished++;
      }
   }
   return mergedArr;
}
0

Source: https://habr.com/ru/post/1666807/


All Articles