Here's the code I wrote:
function mergeSort(array){
if(array.length < 2) return array;
var mid = Math.floor(array.length / 2);
var left = array.slice(0, mid);
var right = array.slice(mid, array.length);
return merge(mergeSort(left), mergeSort(right));
}
function merge(left, right){
var result = [];
while (left.length && right.length){
if(left[0]>right[0]){
result.push(right[0]);
} else {
result.push(left[0]);
}
}
while(left.length){
result.push(left[0]);
}
while(right.length){
result.push(right[0]);
}
return result;
}
array = [1000, -94, -115, 300, 22]
mergeSort(array);
and below is another solution i found online
function mergeSort (arr) {
if (arr.length < 2) return arr;
var mid = Math.floor(arr.length /2);
return merge(mergeSort(arr.slice(0,mid)), mergeSort(arr.slice(mid)));
}
function merge (a,b) {
var result = [];
while (a.length >0 && b.length >0)
result.push(a[0] < b[0]? a.shift() : b.shift());
return result.concat(a.length? a : b);
}
var test = [-100,3,53,21,4,0];
console.log(mergeSort(test));
in comparison I can't find any significant difference besides some syntax. But for some reason mine code won't run in both chrome dev console and node.js environment. In chrome, it won't return any result and in node.js it gives me
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory Abort trap: 6
Can someone help me understand what is the difference between the two snippet that actually made the difference?
Thanks in advance!