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编程递归线性搜索数组中元素的示例。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP