合并排序超出最大调用堆栈大小

Maximum call stack size exceeded in merge sort

我正在研究合并排序并在 JavaScript 中实现它,但它返回了一个错误:

function mergeSort(input) {

RangeError: Maximum call stack size exceeded

这是我的代码:

var array = [2,4,6,7,1,3,5,10,9,8];

// using merge sort: (best sort => O (n log n))
function mergeSort (array) {
var array1 = [];
var array2 = [];

for (let i = 0; i < array.length/2; i++) {
    array1.push(array[i]);
}

for (let i = array.length/2; i < array.length; i++) {
    array2.push(array[i]);
}

array1 = mergeSort(array1);
array2 = mergeSort(array2);

return merge(array1, array2);
}

function merge(a, b) {
let c = [];

while(a.length > 0 && b.length > 0) {
    if (a[0] > b[0]) {
        c.push(b[0]);
        b.splice(0, 1);
    } else {
        c.push(a[0]);
        a.splice(0, 1);
    }
}

while (a.length > 0) {
    c.push(a[0]);
    a.splice(0, 1);
}

while (b.length > 0) {
    c.push(b[0]);
    b.splice(0, 1);
}

return c;
}

console.log(mergeSort(array));

我猜错误在 mergeSort 函数中。我正在用递归实现它。

这个特殊原因与 mergeSort 函数内部的无限递归有关。你叫它越来越深,没有任何条件停止。所以 mergeSort 应该这样重写:

function mergeSort(input) {
  // Here is your recursion stop condition
  if (input.length === 1) return input;

  const median = Math.floor(input.length / 2);

  // Limit arrays should get sliced with each iteration
  const limitA = input.slice(0, median);
  const limitB = input.slice(median);

  return merge(
    mergeSort(limitA), mergeSort(limitB)
  );
};