Recursion and stack

Two ways of thinking

// 創造 pow(x, n) 帶入參數得到 x 的 n 次方 
pow(x, n) = x**n
pow(2, 3) = 8
pow(2, 4) = 16

// 有 2 種思維模式
// 第 1 種用迴圈
function pow(x, n) {
  let result = 1;
  // multiply result by x n times in the loop
  for (let i = 0; i < n; i++) {
    result *= x;
  }
  return result;
}
alert( pow(2, 3) ); // 8

// 第 2 種用遞回
function pow(x, n) {
  if (n == 1) {
    return x;
  } else {
    return x * pow(x, n - 1);
  }
}
alert( pow(2, 3) ); // 8

              if n==1  = x // 遞回基礎
             /
pow(x, n) =
             \
              else     = x * pow(x, n - 1)

// 遞回函式通常比較簡短       
function pow(x, n) {
  return (n == 1) ? x : (x * pow(x, n - 1));
}

// 巢狀函式使用次數有限制,10,000次是可以的,次數依據引擎不同而有差異,這限制遞回的使用,但遞回仍被
// 廣泛應用,因為讓程式碼更簡單更容易維護

The execution context and stack

當函式執行巢狀函式時,會發生以下步驟

  • 目前函式停止執行

  • 執行內容被儲存到課書資料結構 execution context stack

  • 執行巢狀函式

  • 當巢狀函式執行完畢取回原本的韓式繼續執行

Recursive traversals

Recursive structures

除上述的公司組織是遞回,在網頁端 HTML、XML 也是遞回結構,HTML 標籤裡面包含內容、註解、其他HTML 標籤,以下在舉一個遞回例子,某些情況他會優於 array。

Last updated

Was this helpful?