Swift - 遞迴



Swift中的遞迴

遞迴是一種技術,其中函式直接或間接地呼叫自身來解決問題。它不是一次性解決整個問題,而是將問題分解成更小的子問題,然後透過反覆呼叫自身來解決這些子問題,直到達到基本條件。遞迴函式有兩個主要組成部分:

  • 基本條件 - 基本條件負責停止遞迴呼叫。或者說它是一個終止點,防止函式無限地呼叫自身。如果在遞迴函式中沒有指定基本條件,那麼它將無限地呼叫自身,程式將永遠不會結束。

  • 遞迴呼叫 - 遞迴呼叫是指函式使用修改後的引數呼叫自身來解決任務。透過迭代,遞迴呼叫應該朝著基本條件移動,以便它能夠成功終止而不會進入無限遞迴。

語法

以下是遞迴函式的語法:

func functionName(){
   // body
   functionName()
}
functionName()

Swift中遞迴的工作原理

如果在一個函式內部呼叫自身,則稱為遞迴函式。Swift支援函式遞迴。讓我們透過一個例子來了解遞迴的工作原理。

示例

使用遞迴的Swift程式,用於查詢給定數字的階乘:

import Foundation

// Function to find the factorial of the specified number
func factorial(number: Int) -> Int {

   // Base condition
   if number == 0 || number == 1 {
      return 1
   } else {
    
      // Recursive call with modified parameters
      return number * factorial(number:number - 1)
   }
}
let num = 4
let output = factorial(number: num)
print("Factorial of \(num) is: \(output)")

輸出

它將產生以下輸出:

Factorial of 4 is: 24

在上面的程式碼中,我們有一個名為factorial()的遞迴函式。因此,該函式的工作原理如下:

1st function call with 4: factorial(4) = 4 * factorial(3)
2nd function call with 3: factorial(3) = 3 * factorial(2)
3rd function call with 2: factorial(2) = 2 *  factorial(1)
4th function call with 1: factorial(1) = 1(Here the value meets the base condition and the recursive call terminated)
Returned from 4th function call: 1 * 1 = 1
Returned from 3rd function call: 2 * 1 = 2
Returned from 2nd function call: 3 * 2 = 6
Returned from 1st function call: 4 * 6 = 24
Hence the factorial of 4 is 24.

示例

使用二分查詢的Swift程式,用於查詢指定元素的索引:

import Foundation

// Function to find a number from the given array using binary search
func binarySearchAlgorithm(_ arr: [Int], num: Int, leftNum: Int, rightNum: Int) -> Int? {
   if leftNum > rightNum {
      return nil
   }
    
   let midValue = leftNum + (rightNum - leftNum) / 2
    
   if arr[midValue] == num {
      return midValue
   } else if arr[midValue] < num {
      return binarySearchAlgorithm(arr, num: num, leftNum: midValue + 1, rightNum: rightNum)
   } else {
      return binarySearchAlgorithm(arr, num: num, leftNum: leftNum, rightNum: midValue - 1)
   }
}

let myArray = [11, 12, 13, 14, 15, 16, 17, 18, 19]
if let resIndex = binarySearchAlgorithm(myArray, num: 16, leftNum: 0, rightNum: myArray.count - 1) {
   print("Element found at index \(resIndex)") 
} else {
   print("Element Not found")
}

輸出

它將產生以下輸出:

Element found at index 5

Swift中遞迴的必要性

遞迴是一種非常容易地解決大型程式設計問題的強大技術。我們可以在以下場景中使用遞迴:

  • 分治法 - 遞迴演算法使用分治法,它們將複雜問題分解成小的相同子問題,並在每次遞迴呼叫中解決這些子問題。

  • 樹和圖遍歷 - 遞迴函式通常用於遍歷資料結構中的樹和圖。

  • 程式碼可讀性 - 與迭代方法相比,遞迴結果更易於閱讀和管理。

  • 數學計算 - 使用遞迴,我們可以解決各種數學問題,例如階乘、斐波那契數等。

  • 自然表示 - 遞迴為具有遞迴屬性的問題提供了自然和直觀的表示。

遞迴的優點和缺點

以下是遞迴的優點

  • 遞迴函式易於除錯,因為每次遞迴呼叫都專注於任務的一小部分,這允許更具針對性的測試和除錯。

  • 遞迴函式通常使用並行處理,從而提高其效能。

  • 遞迴解決方案更易於閱讀和維護。

  • 遞迴函式靈活且允許抽象。

以下是遞迴的缺點

  • 處理更復雜的問題時,遞迴的執行流程難以跟蹤。

  • 它比迭代迴圈的開銷更大。

  • 如果我們沒有提供正確的基本條件,它將導致無限遞迴。

  • 遞歸併不適用於所有型別的問題,有些問題更適合用迭代方法解決。

廣告