Python program to search for elements in array
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.
它被认为是所有其他搜索算法中最简单和最容易的。但是,这个算法的唯一缺点是效率不高。这就是为什么不经常使用线性搜索的主要原因。
算法
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)
在下面的例子中,我们将学习使用递归方法在数组中进行线性搜索的过程。
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
这是二分搜索算法的工作原理。根据时间复杂度的概念,我们可以肯定二分搜索算法比线性搜索算法更高效,时间复杂度在其中起着重要的作用。通过使用这种类型的算法,可以搜索数组中的元素。尽管用于解决问题的过程不同,但结果不会波动。这是使用多种算法检查输出一致性的一个优点。
The above is the detailed content of Python program to search for elements in array. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Using Notepad++ to run a Python program requires the following steps: 1. Install the Python plug-in; 2. Create a Python file; 3. Set the run options; 4. Run the program.

PyCharm is a very popular Python integrated development environment (IDE). It provides a wealth of functions and tools to make Python development more efficient and convenient. This article will introduce you to the basic operation methods of PyCharm and provide specific code examples to help readers quickly get started and become proficient in operating the tool. 1. Download and install PyCharm First, we need to go to the PyCharm official website (https://www.jetbrains.com/pyc

PyCharm is a powerful Python integrated development environment that provides a wealth of functions and tools to help developers improve efficiency. Among them, PyInstaller is a commonly used tool that can package Python code into an executable file (EXE format) to facilitate running on machines without a Python environment. In this article, we will introduce how to use PyInstaller in PyCharm to package Python code into EXE format, and provide specific

Does PyCharm Community Edition support enough plugins? Need specific code examples As the Python language becomes more and more widely used in the field of software development, PyCharm, as a professional Python integrated development environment (IDE), is favored by developers. PyCharm is divided into two versions: professional version and community version. The community version is provided for free, but its plug-in support is limited compared to the professional version. So the question is, does PyCharm Community Edition support enough plug-ins? This article will use specific code examples to

Llama3 is here! Just now, Meta’s official website was updated and the official announced Llama 38 billion and 70 billion parameter versions. And it is an open source SOTA after its launch: Meta official data shows that the Llama38B and 70B versions surpass all opponents in their respective parameter scales. The 8B model outperforms Gemma7B and Mistral7BInstruct on many benchmarks such as MMLU, GPQA, and HumanEval. The 70B model has surpassed the popular closed-source fried chicken Claude3Sonnet, and has gone back and forth with Google's GeminiPro1.5. As soon as the Huggingface link came out, the open source community became excited again. The sharp-eyed blind students also discovered immediately

The Python program development process includes the following steps: Requirements analysis: clarify business needs and project goals. Design: Determine architecture and data structures, draw flowcharts or use design patterns. Writing code: Program in Python, following coding conventions and documentation comments. Testing: Writing unit and integration tests, conducting manual testing. Review and Refactor: Review code to find flaws and improve readability. Deploy: Deploy the code to the target environment. Maintenance: Fix bugs, improve functionality, and monitor updates.

What is GIL? GIL is the abbreviation of global interpreter lock, which is an important concept of python interpreter. The GIL ensures that the Python interpreter can only execute one thread at a time. This means that at any time, only one thread can run Python bytecode. Other threads must wait for the GIL to be available before continuing execution. How does GIL work? The GIL is a lock written in C and located in the Python interpreter. When a thread wants to execute Python bytecode, it must first obtain the GIL. If the GIL is already held by another thread, that thread must wait for the GIL to be available before continuing execution. What impact does the GIL have on Python programs? GIL for Python

Flask installation and configuration tutorial: A tool to easily build Python Web applications, specific code examples are required. Introduction: With the increasing popularity of Python, Web development has become one of the necessary skills for Python programmers. To carry out web development in Python, we need to choose a suitable web framework. Among the many Python Web frameworks, Flask is a simple, easy-to-use and flexible framework that is favored by developers. This article will introduce the installation of Flask framework,
