
线性搜索是在数组中搜索元素的最简单方法。它是一种顺序搜索算法,从一端开始,并检查数组的每个元素,直到找到所需的元素。
递归是指一个函数调用自身,当使用递归函数时,我们需要使用任何循环来生成迭代。下面的语法演示了简单递归函数的工作原理。
def rerecursiveFun(): Statements ... rerecursiveFun() ... rerecursiveFun
从数组中递归地线性搜索一个元素,只能通过使用函数来实现。在Python中,要定义一个函数,我们需要使用def关键字。
在本文中,我们将学习如何在Python中递归线性搜索数组中的元素。在这里,我们将使用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编程递归线性搜索数组中元素的示例。
以上就是Python程序递归线性搜索数组中的元素的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号