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

WBOY
发布: 2023-08-20 23:22:30
转载
1144人浏览过

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

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

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

def rerecursiveFun():
   Statements
   ...   
   rerecursiveFun()
   ...
rerecursiveFun
登录后复制

递归地线性搜索元素

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

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

立即学习Python免费学习笔记(深入)”;

Example

我们将通过递减数组的大小来递归调用函数 recLinearSearch()。如果数组的大小变为负数,意味着该元素不在数组中,我们返回 -1。如果找到匹配项,则返回元素所在的索引位置。

纳米搜索
纳米搜索

纳米搜索:360推出的新一代AI搜索引擎

纳米搜索 30
查看详情 纳米搜索
# 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中文网其它相关文章!

python速学教程(入门到精通)
python速学教程(入门到精通)

python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号