0

0

Python程序在数组中搜索元素

王林

王林

发布时间:2023-09-17 19:45:03

|

1417人浏览过

|

来源于tutorialspoint

转载

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 -1
arr = [2, 3, 5, 7, 9, 1, 4, 6, 8, 10]
max_size = len(arr)
key = 8
result = 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)

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

行业贸易网站管理系统 2007 Beta 1
行业贸易网站管理系统 2007 Beta 1

1.修正BUG站用资源问题,优化程序2.增加关键词搜索3.修改报价4.修正BUG 水印问题5.修改上传方式6.彻底整合论坛,实现一站通7.彻底解决群发垃圾信息问题。注册会员等发垃圾邮件7.彻底解决数据库安全9.修改交易方式.增加网站担保,和直接交易两中10.全站可选生成html.和单独新闻生成html(需要装组建)11. 网站有10中颜色选择适合不同的行业不同的颜色12.修改竞价格排名方式13.修

下载
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 = 8
result = 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 <= last:
      mid = (first + last) // 2 
   if arr[mid] == key_element:
      return mid
   elif arr[mid] > 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:
         first = mid + 1 

      elif 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速学教程(入门到精通)
python速学教程(入门到精通)

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

下载

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
Sass和less的区别
Sass和less的区别

Sass和less的区别有语法差异、变量和混合器的定义方式、导入方式、运算符的支持、扩展性等。本专题为大家提供Sass和less相关的文章、下载、课程内容,供大家免费下载体验。

212

2023.10.12

if什么意思
if什么意思

if的意思是“如果”的条件。它是一个用于引导条件语句的关键词,用于根据特定条件的真假情况来执行不同的代码块。本专题提供if什么意思的相关文章,供大家免费阅读。

835

2023.08.22

while的用法
while的用法

while的用法是“while 条件: 代码块”,条件是一个表达式,当条件为真时,执行代码块,然后再次判断条件是否为真,如果为真则继续执行代码块,直到条件为假为止。本专题为大家提供while相关的文章、下载、课程内容,供大家免费下载体验。

104

2023.09.25

CSS position定位有几种方式
CSS position定位有几种方式

有4种,分别是静态定位、相对定位、绝对定位和固定定位。更多关于CSS position定位有几种方式的内容,可以访问下面的文章。

83

2023.11.23

页面置换算法
页面置换算法

页面置换算法是操作系统中用来决定在内存中哪些页面应该被换出以便为新的页面提供空间的算法。本专题为大家提供页面置换算法的相关文章,大家可以免费体验。

482

2023.08.14

页面置换算法
页面置换算法

页面置换算法是操作系统中用来决定在内存中哪些页面应该被换出以便为新的页面提供空间的算法。本专题为大家提供页面置换算法的相关文章,大家可以免费体验。

482

2023.08.14

Golang 测试体系与代码质量保障:工程级可靠性建设
Golang 测试体系与代码质量保障:工程级可靠性建设

Go语言测试体系与代码质量保障聚焦于构建工程级可靠性系统。本专题深入解析Go的测试工具链(如go test)、单元测试、集成测试及端到端测试实践,结合代码覆盖率分析、静态代码扫描(如go vet)和动态分析工具,建立全链路质量监控机制。通过自动化测试框架、持续集成(CI)流水线配置及代码审查规范,实现测试用例管理、缺陷追踪与质量门禁控制,确保代码健壮性与可维护性,为高可靠性工程系统提供质量保障。

6

2026.02.28

Golang 工程化架构设计:可维护与可演进系统构建
Golang 工程化架构设计:可维护与可演进系统构建

Go语言工程化架构设计专注于构建高可维护性、可演进的企业级系统。本专题深入探讨Go项目的目录结构设计、模块划分、依赖管理等核心架构原则,涵盖微服务架构、领域驱动设计(DDD)在Go中的实践应用。通过实战案例解析接口抽象、错误处理、配置管理、日志监控等关键工程化技术,帮助开发者掌握构建稳定、可扩展Go应用的最佳实践方法。

6

2026.02.28

Golang 性能分析与运行时机制:构建高性能程序
Golang 性能分析与运行时机制:构建高性能程序

Go语言以其高效的并发模型和优异的性能表现广泛应用于高并发、高性能场景。其运行时机制包括 Goroutine 调度、内存管理、垃圾回收等方面,深入理解这些机制有助于编写更高效稳定的程序。本专题将系统讲解 Golang 的性能分析工具使用、常见性能瓶颈定位及优化策略,并结合实际案例剖析 Go 程序的运行时行为,帮助开发者掌握构建高性能应用的关键技能。

8

2026.02.28

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
最新Python教程 从入门到精通
最新Python教程 从入门到精通

共4课时 | 22.5万人学习

Django 教程
Django 教程

共28课时 | 4.6万人学习

Excel 教程
Excel 教程

共162课时 | 19.4万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

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