Open In App

Searching Algorithms in Python

Last Updated : 01 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Searching algorithms are fundamental techniques used to find an element or a value within a collection of data. In this tutorial, we’ll explore some of the most commonly used searching algorithms in Python. These algorithms include Linear Search, Binary Search, Interpolation Search, and Jump Search.

1. Linear Search

Linear search is the simplest searching algorithm. It sequentially checks each element of the list until it finds the target value.

Steps:

  • Start from the first element of the list.
  • Compare each element of the list with the target value.
  • If the element matches the target value, return its index.
  • If the target value is not found after iterating through the entire list, return -1.

Implementation of Linear Search in Python:

Python
def linear_search(arr, target):
    """
    Perform linear search to find the target value in the given list.

    Parameters:
        arr (list): The list to be searched.
        target: The value to be searched for.

    Returns:
        int: The index of the target value if found, otherwise -1.
    """
    for i in range(len(arr)):
        if arr[i] == target:
            return i
    return -1

# Example usage:
arr = [2, 3, 4, 10, 40]
target = 10
result = linear_search(arr, target)
if result != -1:
    print(f"Linear Search: Element found at index {result}")
else:
    print("Linear Search: Element not found")

Output
Linear Search: Element found at index 3


2. Binary Search

Binary search is a more efficient searching algorithm suitable for sorted lists. It repeatedly divides the search interval in half until the target value is found.

Steps:

  1. Start with the entire sorted list.
  2. Compute the middle element of the list.
  3. If the middle element is equal to the target value, return its index.
  4. If the middle element is less than the target value, search in the right half of the list.
  5. If the middle element is greater than the target value, search in the left half of the list.
  6. Repeat steps 2-5 until the target value is found or the search interval is empty.

Implementation of Binary Search in Python (Recursive):

Python
def binary_search(arr, target, low, high):
    """
    Perform binary search recursively to find the target value in the given sorted list.

    Parameters:
        arr (list): The sorted list to be searched.
        target: The value to be searched for.
        low (int): The lower index of the search interval.
        high (int): The upper index of the search interval.

    Returns:
        int: The index of the target value if found, otherwise -1.
    """
    if low <= high:
        mid = (low + high) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            return binary_search(arr, target, mid + 1, high)
        else:
            return binary_search(arr, target, low, mid - 1)
    else:
        return -1

# Example usage:
arr = [2, 3, 4, 10, 40]
target = 10
result = binary_search(sorted(arr), target, 0, len(arr) - 1)
if result != -1:
    print(f"Binary Search: Element found at index {result}")
else:
    print("Binary Search: Element not found")

Output
Binary Search: Element found at index 3


3. Interpolation Search

Interpolation search is an improved version of binary search, especially suitable for large and uniformly distributed arrays. It calculates the probable position of the target value based on the value of the key and the range of the search space.

Steps:

  1. Calculate the probable position of the target value using interpolation formula.
  2. Compare the target value with the element at the calculated position.
  3. If the element matches the target value, return its index.
  4. If the element is less than the target value, search in the right half of the list.
  5. If the element is greater than the target value, search in the left half of the list.
  6. Repeat steps 1-5 until the target value is found or the search interval is empty.

Implementation of Interpolation Search in Python:

Python
import math

def interpolation_search(arr, target):
    """
    Perform interpolation search to find the target value in the given sorted list.

    Parameters:
        arr (list): The sorted list to be searched.
        target: The value to be searched for.

    Returns:
        int: The index of the target value if found, otherwise -1.
    """
    low = 0
    high = len(arr) - 1
    while low <= high and target >= arr[low] and target <= arr[high]:
        pos = low + ((high - low) // (arr[high] - arr[low])) * (target - arr[low])
        if arr[pos] == target:
            return pos
        elif arr[pos] < target:
            low = pos + 1
        else:
            high = pos - 1
    return -1

# Example usage:
arr = [2, 3, 4, 10, 40]
target = 10
result = interpolation_search(sorted(arr), target)
if result != -1:
    print(f"Interpolation Search: Element found at index {result}")
else:
    print("Interpolation Search: Element not found")

Output
Interpolation Search: Element found at index 3

4. Jump Search

Jump search is another searching algorithm suitable for sorted arrays. It jumps ahead by a fixed number of steps and then performs a linear search in the smaller range.

Steps:

  1. Determine the block size to jump ahead.
  2. Jump ahead by block size until the target value is greater than the current block’s last element.
  3. Perform linear search within the current block to find the target value.
  4. If the target value is found, return its index.
  5. If the target value is not found after iterating through all blocks, return -1.

Implementation of Jump Search in Python:

Python
import math

def jump_search(arr, target):
    """
    Perform jump search to find the target value in the given sorted list.

    Parameters:
        arr (list): The sorted list to be searched.
        target: The value to be searched for.

    Returns:
        int: The index of the target value if found, otherwise -1.
    """
    n = len(arr)
    step = int(math.sqrt(n))
    prev = 0
    while arr[min(step, n) - 1] < target:
        prev = step
        step += int(math.sqrt(n))
        if prev >= n:
            return -1
    while arr[prev] < target:
        prev += 1
        if prev == min(step, n):
            return -1
    if arr[prev] == target:
        return prev
    return -1

# Example usage:
arr = [2, 3, 4, 10, 40]
target = 10
result = jump_search(sorted(arr), target)
if result != -1:
    print(f"Jump Search: Element found at index {result}")
else:
    print("Jump Search: Element not found")

Output
Jump Search: Element found at index 3

Conclusion

In this tutorial, we’ve covered four fundamental searching algorithms in Python: Linear Search, Binary Search, Interpolation Search, and Jump Search. Each algorithm has its advantages and is suitable for different scenarios. Understanding these algorithms and their implementations will help you effectively search for elements within a collection of data.



Similar Reads

Searching Algorithms in Java
Searching Algorithms are designed to check for an element or retrieve an element from any data structure where it is stored. Based on the type of search operation, these algorithms are generally classified into two categories: Sequential Search: In this, the list or array is traversed sequentially and every element is checked. For Example: Linear S
5 min read
Difference between Searching and Sorting Algorithms
Prerequisite: Searching and Sorting Algorithms Searching Algorithms are designed to check for an element or retrieve an element from any data structure where it is used. Based on the type of operations these algorithms are generally classified into two categories: Sequential Search: The Sequential Search is the basic and simple Searching Algorithm.
4 min read
Searching Algorithms for 2D Arrays (Matrix)
Linear Search in 2D Array: Linear search is a simple and sequential searching algorithm. It is used to find whether a particular element is present in the array or not by traversing every element in the array. While searching in the 2D array is exactly the same but here all the cells need to be traversed In this way, any element is searched in a 2D
13 min read
Searching Algorithms
Searching algorithms are essential tools in computer science used to locate specific items within a collection of data. These algorithms are designed to efficiently navigate through data structures to find the desired information, making them fundamental in various applications such as databases, web search engines, and more. Table of Content What
5 min read
Python Program For Searching An Element In A Linked List
Write a function that searches a given key 'x' in a given singly linked list. The function should return true if x is present in linked list and false otherwise. bool search(Node *head, int x) For example, if the key to be searched is 15 and linked list is 14-&gt;21-&gt;11-&gt;30-&gt;10, then function should return false. If key to be searched is 1
4 min read
Iterative searching in Binary Search Tree
Given a binary search tree and a key. Check the given key exists in BST or not without recursion. Please refer binary search tree insertion for recursive search. C/C++ Code // C++ program to demonstrate searching operation // in binary search tree without recursion #include &lt;bits/stdc++.h&gt; using namespace std; struct Node { int data; struct N
7 min read
Pattern Searching using C++ library
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function that prints all occurrences of pat[] in txt[]. You may assume that n &gt; m.Examples: Input : txt[] = "geeks for geeks" pat[] = "geeks" Output : Pattern found at index 0 Pattern found at index 10 Input : txt[] = "aaaa" pat[] = "aa" Output : Pattern found at index 0 Pattern found a
3 min read
Array range queries for searching an element
Given an array of N elements and Q queries of the form L R X. For each query, you have to output if the element X exists in the array between the indices L and R(included). Prerequisite : Mo's Algorithms Examples : Input : N = 5 arr = [1, 1, 5, 4, 5] Q = 3 1 3 2 2 5 1 3 5 5 Output : No Yes Yes Explanation : For the first query, 2 does not exist bet
15+ min read
Octree | Insertion and Searching
Octree is a tree data structure in which each internal node can have at most 8 children. Like Binary tree which divides the space into two segments, Octree divides the space into at most eight-part which is called as octanes. It is used to store the 3-D point which takes a large amount of space. If all the internal node of the Octree contains exact
7 min read
m-WAY Search Trees | Set-1 ( Searching )
The m-way search trees are multi-way trees which are generalised versions of binary trees where each node contains multiple elements. In an m-Way tree of order m, each node contains a maximum of m - 1 elements and m children.The goal of m-Way search tree of height h calls for O(h) no. of accesses for an insert/delete/retrieval operation. Hence, it
7 min read
Article Tags :
three90RightbarBannerImg