You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用尾递归实现数组拆分?无需传递结果数组参数

Tail-Recursive Array Splitting Without Passing Result Parameter

I've refactored your code to use a tail-recursive approach where the divide function directly returns the final collection of subarrays—no need to pass an output array as a parameter. Here's how it works:

We use a helper function that maintains two state variables:

  • A queue of arrays still needing to be split
  • An accumulator that collects subarrays that are small enough (length ≤2)

Each recursive call to the helper is the final operation in the function, making it tail-recursive (which allows potential engine optimizations in supported environments).

(function(){ 
  'use strict'; 
  mainFunction(); 

  function mainFunction(){ 
    var inputArray = [12,54,76,6,1,88,7,11,66]; 
    console.log("Input Array is ", inputArray);
    // Call divide directly and get the result
    var arrayOfArrays = divide(inputArray); 
    console.log("Output Array is ", arrayOfArrays); 
  } // end of mainFunction

  function divide(numArray) {
    // Tail-recursive helper to handle processing queue and accumulator
    function divideHelper(arraysToProcess, accumulator) {
      // Base case: no more arrays to process, return the final result
      if (arraysToProcess.length === 0) {
        return accumulator;
      }

      // Take the first array from the processing queue
      const [currentArray, ...remainingArrays] = arraysToProcess;
      const pivot = parseInt(currentArray.length / 2);

      if (currentArray.length > 2) {
        // Split into left and right subarrays
        const leftArray = currentArray.slice(0, pivot);
        const rightArray = currentArray.slice(pivot);
        // Add left and right back to the queue (process left first to match original order)
        return divideHelper([leftArray, rightArray, ...remainingArrays], accumulator);
      } else {
        // Array is small enough, add to accumulator and process remaining arrays
        return divideHelper(remainingArrays, [...accumulator, currentArray]);
      }
    }

    // Initialize helper with the input array and empty accumulator
    return divideHelper([numArray], []);
  } // end of divide
})();

Sample Output

When you run this code, you'll get the same output as your original implementation:

E:\DataStructuresAndAlgorithms\array>node divideArray01.js
Input Array is [ 12, 54, 76, 6, 1, 88, 7, 11, 66 ]
Output Array is [ [ 12, 54 ], [ 76, 6 ], [ 1, 88 ], [ 7 ], [ 11, 66 ] ]
E:\DataStructuresAndAlgorithms\array>

Note: For tail call optimization (TCO) to work in Node.js, you may need to run the code with the --harmony-tailcalls flag, though support for TCO in V8 has been limited in recent versions. Regardless, the code follows tail-recursive structure as requested.

内容的提问来源于stack exchange,提问作者Rahul Shivsharan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:38:41