簡體   English   中英

超過合並排序調用堆棧

[英]Merge sort call stack exceeded

我擔心這里缺少明顯的東西,但看不到。 在chrome控制台和節點8.4.0中運行此命令,mergeSort會引起RangeError: Maximum call stack size exceeded對於大於長度1的輸入數組, RangeError: Maximum call stack size exceededRangeError: Maximum call stack size exceeded 。merge函數似乎運行良好。 這是代碼:

"use strict";

function merge(A, B) {
  if (!Array.isArray(A) || !Array.isArray(B)) {
    throw new Error("merge expects both of its arguments to be arrays");
  }

  let result = [];
  let [i, j] = [0, 0];

  while (A[i]) {
    if (B[j]) {
      if (A[i] <= B[j]) {
        result.push(A[i]);
        i++;
      } else {
        while (A[i] >= B[j]) {
          result.push(B[j]);
          j++;
        }
        result.push(A[i]);
        i++;
      }
    } else {
      result.push(A[i]);
      i++;
    }
  }

  while (B[j]) {
    result.push(B[j]);
    j++;
  }

  return result;
}

function mergeSort(A) {
  if (!Array.isArray(A)) {
    throw new Error("mergeSort expects its argument to be an array");
  }

  if (A.length === 1) return A;
  let i = A.slice(Math.floor(A.length / 2));
  let R = A.slice(i);
  let L = A.slice(0, i);
  return merge(mergeSort(R), mergeSort(L));
}

i不應該是一個數組。 你只想要

let i = Math.floor(A.length / 2);

同樣,您的基本情況太嚴格了,您的函數也將在空數組上無限遞歸。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM