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

WBOY
WBOY 转载
2023-08-20 23:22:30 557浏览

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

线性搜索是在数组中搜索元素的最简单方法。它是一种顺序搜索算法,从一端开始,并检查数组的每个元素,直到找到所需的元素。

递归是指一个函数调用自身,当使用递归函数时,我们需要使用任何循环来生成迭代。下面的语法演示了简单递归函数的工作原理。

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

递归地线性搜索元素

从数组中递归地线性搜索一个元素,只能通过使用函数来实现。在Python中,要定义一个函数,我们需要使用def关键字。

在本文中,我们将学习如何在Python中递归线性搜索数组中的元素。在这里,我们将使用Python列表代替数组,因为Python没有特定的数据类型来表示数组。

Example

我们将通过递减数组的大小来递归调用函数 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.

Example

让我们来看一个在数组中搜索元素的另一个例子。

# 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.

Example

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

以上就是Python程序递归线性搜索数组中的元素的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除