I have n (n between 1 and 100) sorted number arrays, each with m elements (m around 1000 in my case). I want to merge them into a single sorted array.
I can think of two possibilities for doing this:
1.Use a two arrays merging algo (like merge() function below from http://www.nczonline.net/blog/2012/10/02/computer-science-and-javascript-merge-sort/) and applying it iteratively (1st and 2nd, then merge of 1st-2nd and 3rd, etc)
function merge(left, right) {
var result = [],
il = 0,
ir = 0;
while (il < left.length && ir < right.length){
if (left[il] < right[ir]){
result.push(left[il++]);
} else {
result.push(right[ir++]);
}
}
return result.concat(left.slice(il)).concat(right.slice(ir));
}
- Generalize
merge()function to n arrays simultaneously. At each iteration, I would pick the min value of the n first values not yet processed and append it to the result.
Are these two algo equivalent in terms of complexity ? I have the feeling that both algo are in o(m*n). Am I right ?
Are there any performance consideration to take one algo rather than the other ? I have the feeling that 1 is simpler than 2.