The mergeSort function should return: [2, 2, 3, 4, 6]
PseudoCode
Visual Representation
One Possible Solution
function merge(left, right) {
var outputArray = [];
while(left.length && right.length) {
if (left[0] < right[0]) outputArray.push(left.shift());
else outputArray.push(right.shift());
}
while(left.length) {
outputArray.push(left.shift());
}
while(right.length) {
outputArray.push(right.shift());
}
return outputArray
}
function mergeSort(array) {
if (array.length < 2) return array
var middle = Math.floor(array.length / 2);
var left = array.slice(0, middle);
var right = array.slice(middle);
return merge(mergeSort(left),mergeSort(right));
}
Efficiency
Time Efficiency in all cases (best and worst): O(n log(n))
Since we divide each set to be sorted in half at each level of recursion, there will be log(n) levels. A total of n comparisons must be made at each level, thus O(n log(n))