Home > Backend Development > Python Tutorial > Python program to search for elements in array

Python program to search for elements in array

王林
Release: 2023-09-17 19:45:03
forward
1209 people have browsed it

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))
Copy after login

Output

上述程序的输出如下:

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

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))
Copy after login

Output

上述程序的输出如下:

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

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") 
Copy after login

Output

上述程序的输出如下:

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

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")
Copy after login

Output

上述程序的输出如下:

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

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

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template