Skip to content

Instantly share code, notes, and snippets.

@jtribble
Last active January 20, 2016 17:09
Show Gist options
  • Save jtribble/62ee5953f0f243f357dd to your computer and use it in GitHub Desktop.
Save jtribble/62ee5953f0f243f357dd to your computer and use it in GitHub Desktop.
//
// See: http://www.glassdoor.com/Interview/You-are-given-a-collection-of-M-arrays-with-N-integers-Every-array-is-sorted-Develop-an-algorithm-to-combine-each-array-i-QTN_1195702.htm
//
// You are given a collection of M arrays with N integers. Every array is sorted.
// Develop an algorithm to combine each array into one sorted array.
//
var mergeSortedLists = (function () {
/**
* Merge (given two sorted arrays, return a single sorted array)
*
* @param {array} left
* @param {array} right
* @return {array}
*/
var merge = function (left, right) {
// store resulting array
var sorted = [];
// loop through lists and compare elements front to back, until either list is empty
while (left.length > 0 && right.length > 0) {
(left[0] <= right[0]) ? sorted.push(left.shift()) : sorted.push(right.shift());
}
// add any remaining items
while (left.length > 0) sorted.push(left.shift());
while (right.length > 0) sorted.push(right.shift());
// return sorted list
return sorted;
};
return function (arrays) {
return arrays.reduce(function (acc, curr) {
return merge(acc, curr);
}, []);
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment