Python程序在数组中搜索元素

python程序在数组中搜索元素

In Python, there are mainly two searching algorithms that are majorly used. Out of those, the first one is Linear Search and the second one is Binary Search.

These two techniques are majorly used in order to search an element from the given array or from the given list also. While searching an element, there are two methodologies that can be followed in any kind of algorithm. One of those is recursive approach and the other is iterative approach. Let us discuss both algorithms in both approaches and solve similar problems.

Linear Search

The Linear Search technique is also known as Sequential search. The meaning of the name “ Sequential search ” is definitely justified by the process followed by this search algorithm. It is a method or technique which is used in order to find the elements within an array or a list in Python.

它被认为是所有其他搜索算法中最简单和最容易的。但是,这个算法的唯一缺点是效率不高。这就是为什么不经常使用线性搜索的主要原因。

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

算法

Step 1 − It searches for an element in a sequential order just by comparing the desired element with each element present in the given array.

步骤 2 − 如果找到所需的元素,则会将元素的索引或位置显示给用户。

Step 3 − If the element is not present within the array, then the user will be informed that the element is not found. In this way, the algorithm is processed.

In general, Linear search algorithm is comparatively suitable and efficient for small arrays or small lists which has a size less than or equal to 100 as it checks and compares with each element.

如果所需元素位于数组的最后位置,将会消耗更多时间。

线性搜索算法在最佳情况下的时间复杂度为“ O( 1 ) ”。在这种情况下,元素将位于数组的第一个位置,即索引为“ 0 ”。

The Time complexity of Linear Search algorithm in average case is “ O( n ) ”. In this case, the element will be present in the middle position of the array, i.e., with the index “ ( n – 1 ) / 2 ” or “ (( n – 1 ) / 2 )+ 1 ”.

The Time complexity of Linear Search algorithm in worst case is “ O( n ) ”. In this case, the element will be present in the last position of the array, i.e., with the index “ n-1 ”.

Example

在下面的示例中,我们将学习使用线性搜索在数组中查找元素的过程。

def iterative_linear( arr, n, key_element):   for x in range(n):      if(arr[x] == key_element):         return x   return -1arr = [2, 3, 5, 7, 9, 1, 4, 6, 8, 10]max_size = len(arr)key = 8result = iterative_linear(arr, max_size - 1, key)if result != -1:   print ("The element", key," is found at the index " ,(result), "and in the ", (result+1), "position")else:   print ("The element %d is not present in the given array" %(key))

Output

上述程序的输出如下:

The element 8  is found at the index  8 and in the  9 position

Example (Recursive)

在下面的例子中,我们将学习使用递归方法在数组中进行线性搜索的过程。

def recursive_linear( arr, first_index, last_index, key_element):   if last_index < first_index:      return -1   if arr[first_index] == key_element:      return first_index   if arr[last_index] == key_element:      return last_index     return recursive_linear(arr, first_index + 1, last_index - 1, key_element)arr = [2, 3, 5, 7, 9, 1, 4, 6, 8, 10]max_size = len(arr)key = 8result = recursive_linear(arr, 0, max_size - 1, key)if result != -1:   print ("The element", key," is found at the index " ,(result), "and in the ", (result+1), "position")else:   print ("The element %d is not present in the given array" %(key))

Output

上述程序的输出如下:

The element 8  is found at the index  8 and in the  9 position

Binary Search

二分查找算法与线性查找算法相当不同。它遵循完全不同的过程来搜索数组中的元素。它通常只考虑有序数组。

如果数组在某些情况下没有排序,则对数组进行排序,然后开始二分搜索算法的过程。一旦数组被二分搜索算法考虑,它首先被排序,然后算法被应用于数组。

算法

步骤 1 − 对数组进行排序是第一步。

Step 2 − After the array is sorted, the array is considered as two halves. One half is starting from the first element to the middle element of the sorted array and the second half is starting from the element after the middle element to the last element of the sorted array.

Step 3 − The key element (the element that is supposed to be searched is known as key element) is compared with the middle element of the sorted array.

Step 4 − If the key element is less than or equal to the middle element of the sorted array, the second half elements are ignored further as the key element is smaller than the middle element. So, definitely, the element must be present in between the first element and the middle element.

Step 6 − If the key element is greater than the middle element, then the first half of the sorted array is ignored and the elements from the middle element to the last element are considered.

Step 7 − Out of those elements, the key element is again compared with the middle element of the halved array and repeats the same procedure. If the key element is greater than the middle element of the halved array, then the first half is neglected.

第8步 – 如果关键元素小于或等于被分割数组的中间元素,则被分割数组的后半部分将被忽略。通过这种方式,元素将在数组的任意一半中进行搜索。

因此,与线性搜索相比,复杂度减少了一半或更多,因为有一半的元素将在第一步中被移除或不被考虑。二分搜索的最佳情况时间复杂度为“O(1)”。二分搜索的最坏情况时间复杂度为“O(logn)”。这就是二分搜索算法的工作原理。让我们考虑一个例子,并应用二分搜索算法来找出数组中的关键元素。

Example

In this example, we are going to learn about the process of searching an element in an array using Binary search in recursive approach.

def recursive_binary(arr, first, last, key_element):   if first  key_element:      return recursive_binary(arr, first, mid - 1, key_element)   elif arr[mid] < key_element:        return recursive_binary(arr, mid + 1, last, key_element)     else:        return -1 arr = [20, 40, 60, 80, 100] key = 80 max_size = len(arr)result = recursive_binary(arr, 0, max_size - 1, key)  if result != -1:     print("The element", key, "is present at index", (result), "in the position", (result + 1)) else:     print("The element is not present in the array") 

Output

上述程序的输出如下:

The element 80  is found at the index 3 and in the position 4

Example

In this example, we are going to learn about the process of searching an element in an array using Binary search in iterative approach.

def iterative_binary(arr, last, key_element):   first = 0   mid = 0   while first <= last:       mid = (first + last) // 2       if arr[mid]  key_element:          last = mid - 1       else:          return mid    return -1 arr = [20, 40, 60, 80, 100] key = 80 max_size = len(arr)result = iterative_binary(arr, max_size - 1, key)  if result != -1:     print("The element", key, "is present at index", (result), "in the position", (result + 1)) else:     print("The element is not present in the array")

Output

上述程序的输出如下:

The element 80  is found at the index 3 and in the position 4

这是二分搜索算法的工作原理。根据时间复杂度的概念,我们可以肯定二分搜索算法比线性搜索算法更高效,时间复杂度在其中起着重要的作用。通过使用这种类型的算法,可以搜索数组中的元素。尽管用于解决问题的过程不同,但结果不会波动。这是使用多种算法检查输出一致性的一个优点。

以上就是Python程序在数组中搜索元素的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1342906.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月13日 05:59:33
下一篇 2025年12月13日 05:59:51

相关推荐

  • 获取链表的中间元素的Python程序,在单次迭代中完成

    链表用于将数据存储在不连续的内存位置。包含数据项的节点使用指针链接。每个节点由两个字段组成。第一个字段用于存储数据,第二个字段包含到下一个节点的链接。 暴力破解技术 要找到链表的中间元素,暴力破解技术是通过迭代整个链表直到遇到 NULL 为止来找出链表的长度,然后将长度除以 2 得到链表的索引中间的…

    2025年12月13日
    000
  • PHP如何获取RTSP视频流信息 RTSP视频流获取技巧分享

    php本身不支持直接获取rtsp视频流信息,需借助其他工具或技术实现。1.使用ffmpeg命令行工具:通过php的exec()或shell_exec()函数调用ffmpeg命令,获取并解析视频流元数据;2.使用gstreamer命令行工具:与ffmpeg类似,通过php调用并解析输出结果;3.使用第…

    2025年12月10日 好文分享
    000
  • 如何在LAMP架构中整合Node.js和Python服务?

    在LAMP架构中集成Node.js和Python服务 许多网站都基于LAMP架构(Linux、Apache、MySQL和PHP)构建,但随着项目扩展,可能需要添加Node.js或Python来实现新功能,而这些功能在PHP中实现起来效率较低或根本无法实现。那么,如何在现有的LAMP环境中,让PHP程…

    2025年12月10日
    000
  • 如何在LAMP架构下高效整合Node.js或Python服务?

    在既有LAMP架构中集成Node.js或Python服务 许多网站开发者面临一个挑战:如何将使用Node.js或Python开发的功能模块无缝集成到已有的LAMP(Linux+Apache+MySQL+PHP)架构网站中? 由于Apache通常将80端口请求交给PHP处理,因此需要一种机制来处理No…

    2025年12月10日
    000
  • 如何在不使用context或conversation_id参数的情况下实现ChatGPT的上下文关联?

    ChatGPT API上下文管理技巧:无需context或conversation_id参数 OpenAI的ChatGPT API虽然方便实现简单的问答,但长对话的上下文关联却是个挑战。官方文档并未明确说明如何使用context或conversation_id参数来维护上下文,且使用这些参数往往导致…

    2025年12月10日
    000
  • Python异常处理方法总结

    %ign%ignore_a_1%re_a_1%中的异常处理机制 1、 当Python程序出现语法或逻辑问题时,在执行过程中会触发错误提示。 2、 为了捕获并处理这些错误,可以采用try…except结构来实现异常捕捉。 立即学习“Python免费学习笔记(深入)”; 3、 发生异常时,会…

    2025年12月3日 软件教程
    000
  • Python异常处理:掌握try-except-finally用法

    以下是对您提供的内容进行伪原创后的版本,已保留原始图片位置且未改变文章大意: 在编写Pyth%ignore_a_1%n程序时,异常处理是一个非常关键的部分。了解并掌握如何处理异常,可以有效提升程序的健壮性和用户体验。以下是关于Python异常处理的一些实用技巧。 1、什么是异常?异常是程序运行过程中…

    2025年12月2日 软件教程
    000
  • Python异常处理使用方法精讲

    python程序在执行过程中可能会遇到错误或异常情况,这时就需要进行异常处理。那么该如何实现呢? 1、 首先启动 PyCharm 编辑器,进入 Python 编程环境。 2、 接着打开一个Python文件,并继续添加注释内容。 立即学习“Python免费学习笔记(深入)”; 3、 Python中的异…

    2025年12月2日 软件教程
    000
  • Python入门与使用技巧

    python是一门功能丰富且应用广泛的编程语言,尤其在人工智能、数据分析等领域具有显著优势。下面将详细介绍如何启动python并进行基础操作,助力新手快速入门。 1、 首先,启动Python的第一步是打开命令提示符。可以通过点击电脑的“开始”菜单,在搜索栏或“运行”窗口中输入“cmd”,然后按回车键…

    2025年12月2日 软件教程
    000
  • 如何用Python实时监控浏览器并获取页面域名和数据?

    Python实时监控浏览器并获取页面域名和数据:方法探讨与挑战 本文探讨如何使用python实时监控用户浏览器活动,并获取打开页面的域名及页面数据。直接从python访问浏览器内存或进程获取数据存在安全和权限问题,因此需要间接方法。 挑战与限制: 直接读取浏览器进程信息存在安全风险,可能被操作系统阻…

    2025年12月2日 web前端
    000
  • Go语言文件I/O性能优化:从慢到快的实践指南

    本文探讨了go程序在处理大量文件i/o时可能出现的性能瓶颈,即便是在简单数值计算场景下。通过详尽的性能分析,揭示了`fmt`包直接i/o操作的效率限制。核心解决方案是引入`bufio`包进行缓冲i/o,显著提升了数据读写速度,并详细介绍了使用`bufio`时的关键注意事项,如格式字符串中的换行符处理…

    2025年12月2日 后端开发
    000
  • 优化Go程序I/O性能:从慢速fmt到高效bufio实践

    本文探讨了go程序在处理大量文件i/o时,为何可能出现低于预期的性能表现。通过实际案例分析,揭示了标准库fmt在直接文件操作时可能存在的效率瓶颈。教程详细介绍了如何利用bufio包进行缓冲i/o,并结合正确的格式化字符串和刷新机制,显著提升go程序的i/o处理速度,使其性能达到甚至超越python,…

    2025年12月2日 后端开发
    000
  • Python安装与环境配置

    python于1989年问世,由荷兰程序员吉多·范罗苏姆开发,凭借其易于上手、丰富的库支持、广泛的应用场景以及强大的跨平台特性,赢得了众多编程爱好者的青睐。接下来,让我们一起踏上python的学习之旅。 1、 首先打开Python官方主页,点击获取最新版Python 3.8.4,也可在Downloa…

    2025年12月2日 软件教程
    000
  • 在Python中模拟Go语言的select并发模式

    python标准库中没有直接对应go语言`select`语句的并发原语。本文将探讨如何利用python的`threading`模块和`queue.queue`来实现类似go `select`的功能,即同时监听多个通信通道并处理首先就绪的事件。我们将通过逐步构建和优化代码示例,展示如何模拟go的“选择…

    2025年12月2日 后端开发
    000
  • Python中模拟Go语言的Channel Select机制

    本文深入探讨了go语言中`select`语句的强大并发通信能力,并详细阐述了如何在python环境中,利用`threading`模块和`queue`数据结构,构建一个功能类似的通道选择机制。通过创建独立的监听线程将多个源队列的消息汇集到一个中心队列,python程序能够有效地等待并处理来自不同并发源…

    2025年12月2日 后端开发
    000
  • 海康摄像头App远程控制:如何实现平滑转动以及多设备联动?

    海康摄像头App远程控制技术详解 本文将深入探讨海康摄像头App远程控制技术,特别是如何实现平滑转动和多设备联动。 我们将分析App控制摄像头转动的技术细节和实现流程。 一个典型的应用场景是:App向海康服务器发送指令,服务器再将指令转发给摄像头,从而实现摄像头转动。 这其中是否需要反馈机制?整个流…

    2025年12月2日 java
    000
  • 故障分析工具

    如何快速找出网站故障的根源?php小编香蕉为大家带来了常见的故障分析工具,这些工具可以帮助您快速识别并解决网站故障。通过深入了解这些工具的功能和使用场景,您可以提升您的故障分析技能。 一、故障分析工具 故障分析工具的重要性 在IT行业中,故障分析工具是一个必不可少的工具。它们在帮助企业及时发现和解决…

    2025年12月1日 电脑教程
    100
  • 解决批处理文件无法运行Python脚本的问题:完整指南与调试技巧

    本文详细阐述了如何通过批处理文件(.bat)正确运行Python脚本。针对常见的脚本不执行问题,文章指出核心在于批处理命令的语法错误,即未将Python解释器与脚本文件正确关联。教程提供了正确的批处理命令格式、代码示例,并指导读者如何验证Python环境、利用命令行进行调试,确保Python程序能顺…

    2025年11月29日 后端开发
    000
  • Python中如何操作Hive?PyHive连接方法

    1.pyhive支持的认证方式包括nosasl、kerberos和ldap;2.使用pyhive操作hive时需要注意参数化查询、资源管理、大数据量处理、性能优化和错误处理;3.pyhive可与pandas、pyspark及airflow等工具协同工作。pyhive连接hive常用的认证方式有三种:…

    2025年11月29日 后端开发
    000
  • 如何在Python中从一个Python文件触发并运行另一个Python文件

    本文旨在指导开发者如何在Python中从一个Python脚本启动并执行另一个Python脚本。通常,我们需要在一个Python程序中调用其他Python程序来完成特定的任务,例如数据处理、系统管理等。Python提供了多种方法来实现这一目标,其中subprocess模块是最常用且功能强大的选择。 s…

    2025年11月29日 后端开发
    000

发表回复

登录后才能评论
关注微信