Python遞迴線性搜尋陣列元素程式


線性查詢是在陣列中搜索元素最簡單的方法。它是一種順序搜尋演算法,從一端開始,檢查陣列的每個元素,直到找到所需的元素。

遞迴是指函式呼叫自身,使用遞迴函式時,不需要使用任何迴圈來生成迭代。下面的語法演示了一個簡單的遞迴函式的工作原理。

def rerecursiveFun():
   Statements
   ...   
   rerecursiveFun()
   ...
rerecursiveFun

元素的遞迴線性查詢

僅使用函式才能遞迴地從陣列中線性搜尋元素。要在Python中定義函式,需要使用`def`關鍵字。

在本文中,我們將學習如何在Python中遞迴地線性搜尋陣列中的元素。我們將使用Python列表代替陣列,因為Python沒有特定資料型別來表示陣列。

示例

我們將透過遞減陣列的大小來遞迴呼叫函式`recLinearSearch()`。如果陣列大小小於零,則表示陣列中不存在該元素,我們將返回-1。如果找到匹配項,則返回找到該元素的索引。

# Recursively Linearly Search an Element in an Array  
def recLinearSearch( arr, l, r, x): 
   if r < l: 
      return -1
   if arr[l] == x: 
      return l 
   if arr[r] == x: 
      return r 
   return recLinearSearch(arr, l+1, r-1, x) 
     
lst = [1, 6, 4, 9, 2, 8]
element = 2
res = recLinearSearch(lst, 0, len(lst)-1, element) 
  
if res != -1:
   print('{} was found at index {}.'.format(element, res))
else:
   print('{} was not found.'.format(element))

輸出

2 was found at index 4.

示例

讓我們再舉一個在陣列中搜索元素的例子。

# Recursively Linearly Search an Element in an Array  
def recLinearSearch(arr, curr_index, key):
   if curr_index == -1:
      return -1
   if arr[curr_index] == key:
      return curr_index
   return recLinearSearch(arr, curr_index-1, key)
arr = [1, 3, 6, 9, 12, 15]
element = 6
res = recLinearSearch(arr, len(arr)-1, element) 
  
if res != -1:
   print('{} was found at index {}.'.format(element, res))
else:
   print('{} was not found.'.format(element))

輸出

6 was found at index 2.

示例

再舉一個例子,在陣列中搜索元素100。

# Recursively Linearly Search an Element in an Array  
def recLinearSearch(arr, curr_index, key):
   if curr_index == -1:
      return -1
   if arr[curr_index] == key:
      return curr_index
   return recLinearSearch(arr, curr_index-1, key)     
arr = [1, 3, 6, 9, 12, 15]
element = 100
res = recLinearSearch(arr, len(arr)-1, element) 
  
if res != -1:
   print('{} was found at index {}.'.format(element, res))
else:
   print('{} was not found.'.format(element))

輸出

100 was not found.

在上面的例子中,在給定的陣列中找不到元素100。

這些是使用Python程式設計遞迴線性搜尋陣列中元素的示例。

更新於:2023年5月15日

2K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告