Python 递归线性搜索数组中的元素

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编程递归线性搜索数组中的元素的示例。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程