我正在用 1,000,000 个数字对其进行测试,结果有点悬。我以为它会轻而易举地通过 1,000,000。是我的实现吗?我有一种感觉是因为slice()
,有人有想法吗?
编辑:刚收到这条消息:
FATAL ERROR: CALL_AND_RETRY_2 Allocation failed - process out of memory
TopDownSplitMerge(numbersArray);
function TopDownSplitMerge(arrayOfNumbers) {
var length = arrayOfNumbers.length
var middleIndex = parseInt(length/2);
if(length <= 1) {
return arrayOfNumbers;
}
// Split left side
var left = TopDownSplitMerge(arrayOfNumbers.slice(0, middleIndex));
// Split right side
var right = TopDownSplitMerge(arrayOfNumbers.slice(middleIndex, length));
// Merge every back together
return TopDownMerge(left, right);
}
function TopDownMerge(left, right) {
var results = []
while(left.length || right.length) {
console.log("looping...");
// Check if both sides are NOT empty, if so, then just finish shifting the non-empty side
if(left.length && right.length) {
if(left[0] <= right[0]) {
results.push(left.shift())
} else {
results.push(right.shift())
}
} else if(left.length) {
results.push(left.shift())
} else {
results.push(right.shift())
}
}
console.log("Merging....", results.length);
return results;
}