您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2024/3/9 11:52:59发布34次查看
线性搜索是在数组中搜索元素的最简单方法。它是一种顺序搜索算法,从一端开始,并检查数组的每个元素,直到找到所需的元素。
递归是指一个函数调用自身,当使用递归函数时,我们需要使用任何循环来生成迭代。下面的语法演示了简单递归函数的工作原理。
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 = 2res = 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 = 6res = 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 = 100res = 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程序递归线性搜索数组中的元素的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product