Python Searching Algorithms Tutorial

Searching algorithms represent basic methods for efficiently finding an item within a dataset. They play a crucial role in data processing and problem-solving tasks. This tutorial will discuss the four most commonly employed searching algorithms in Python: Linear Search, Binary Search, Interpolation Search, and Jump Search.

Each of these algorithms employs a diverse approach that ranges from simple sequential searching to advanced position estimation, making them best suited for different kinds of data and performance needs.

Linear Search

The simplest approach is the linear search technique. It systematically examines the elements one by one until the desired value is found.

Steps

  • Start from the first element.
  • Compare each element with the target value.
  • When a match is located, the index is returned.
  • In the case that no matching element is found in the entire list, then -1 is returned.
  • Python Implementation For Linear Search

In this section, we will illustrate how to implement linear search using Python.

Example

def linear_search(arr, target):

    for i in range(len(arr)):

        if arr[i] == target:

            return i

    return -1

Linear Search Example in Python

Let us consider an example to illustrate the linear search algorithm in Python.

Example

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

Output

Linear Search: Element found at index 3

Binary Search

Binary search is a more efficient algorithm; however, it requires the list to be sorted. It continually divides the list in half until it finds the target value.

Steps:

  • Start with the entire sorted list.
  • Find the middle element.
  • When the middle term is the target, then give its position.
  • In case the target is smaller, search the left half.
  • Search the right half in case it is larger.
  • Continue to search until either the target is located or the search interval is cleared.
  • Python Implementation for Binary Search

In this section, we will illustrate how to implement binary search using Python.

Example

def binary_search(arr, target, low, high):

    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)

    return -1

Binary Search Example in Python

Let's consider an example to illustrate the implementation of binary search in Python.

Example

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

Output

Binary Search: Element found at index 3

Interpolation Search

Interpolation search represents an enhanced variant of binary search, particularly effective for extensive and uniformly distributed datasets. Instead of merely examining the midpoint, it makes an estimation of the likely position of the target.

Steps

  • Estimate the most probable position with the interpolation formula.
  • Compare that position element with the target.
  • If equal, return its index.
  • Search the right half in case it is small.
  • Scan the left half of the search in case it is bigger.
  • Repeat until the target or range is empty.
  • Python Implementation for Interpolation Search

In this section, we will illustrate how to implement interpolation search using Python.

Example

def interpolation_search(arr, target):

    low, high = 0, len(arr) - 1

    while low <= high and arr[low] <= target <= arr[high]:

        pos = low + ((high - low) * (target - arr[low])) // (arr[high] - arr[low])

        if arr[pos] == target:

            return pos

        elif arr[pos] < target:

            low = pos + 1

        else:

            high = pos - 1

    return -1

Interpolation Search Example in Python

Consider an example to illustrate the implementation of interpolation search using Python.

Example

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

Output

Interpolation Search: Element found at index 3

Jump Search

Jump Search is a highly effective algorithm utilized for sorted arrays. Instead of inspecting elements in a sequential manner, it examines them using a specified block size, followed by a linear search within the block that has been located at that point.

Steps

  • Choose a block size (often sq n ).
  • Move in block sizing until the target becomes smaller than or equal to the final element on the current block.
  • Perform a linear search within that block.
  • On a find, the index is returned; otherwise, the value -1 is returned.
  • Python Implementation for Jump Search

In this section, we will illustrate how to implement jump search using Python.

Example

import math

def jump_search(arr, target):

    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

Jump Search Example in Python

Consider an example to illustrate the implementation of jump search using Python.

Example

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:

Output

Jump Search: Element found at index 3

Exponential Search

Exponential Search is a method designed for sorted arrays, primarily utilized when the target element resides close to the start. The algorithm operates by establishing a range where the element may be found, followed by executing a binary search within that specified range.

Steps

  • Start with index 1.
  • Check elements are configured at index 1, 2, 4, 8, etc (with exponentially increasing indices) until the target is reached in the value at the index, or the array terminal has been reached.
  • Once the range is known, search binary on the range.
  • On occurrence, give back index or give back -1.
  • Python Implementation for Exponential Search

In this section, we will illustrate how to implement exponential search using Python.

Example

def binary_search(arr, target, low, high):

    while low <= high:

        mid = (low + high) // 2

        if arr[mid] == target:

            return mid

        elif arr[mid] < target:

            low = mid + 1

        else:

            high = mid - 1

    return -1

def exponential_search(arr, target):

    n = len(arr)

    if arr[0] == target:

        return 0

    i = 1

    while i < n and arr[i] <= target:

        i *= 2

    return binary_search(arr, target, i // 2, min(i, n - 1))

Exponential Search Example in Python

Let us consider an illustration to showcase the exponential search algorithm in Python.

Example

arr = [2, 3, 4, 10, 40, 55, 70, 90]

target = 10

result = exponential_search(sorted(arr), target)

if result != -1:

    print(f"Exponential Search: Element found at index {result}")

else:

    print("Exponential Search: Element not found")

Output:

Output

Exponential Search: Element found at index 3

Comparison of Searching Algorithms

Let's compare the searching algorithms discussed in this article based on various factors:

Linear Search Binary Search Interpolation Search Exponential Search Jump Search
Time Complexity O(n) O(log n) O(log log n) O(log n) O(√n)
Space Complexity O(1) O(1) O(1) O(1) O(1)
Use Cases Suitable for small datasets and when the data is unsorted Ideal for large sorted datasets. Effective for uniformly distributed data Works well for unsorted data Efficient for large sorted datasets, especially when the distribution is not uniform
Sorting Requirement No Yes Yes No It works well with ordered data but is able to operate on unordered data.

When to Choose Which Algorithm?

The search algorithm used is determined by the nature of your data and the exact needs. The following are broad-based guidelines to assist in the determination of the algorithm to utilize:

  • Linear Search : Linear search is applicable where the size of the data is small, like when order is not required or the location of the sought element is not known.
  • Binary Search : Select binary search when the size of the data set is large and the set is sorted, and you need to access it efficiently.
  • Interpolation Search : Interpolation search can be a good choice when you have uniformly distributed data that is also sorted.
  • Exponential Search: In unsorted data sets, exponential search may be better than linear search.
  • Jump Search: Jump search is considered to be applied to large and sorted sets of data, particularly when the data distribution is not even.
  • Conclusion

This tutorial covered four primary searching algorithms in Python: Linear Search, Binary Search, Interpolation Search, and Jump Search. Each algorithm employs a distinct approach; certain methods are straightforward but may be less efficient, while others demonstrate improved performance when applied to sorted datasets or uniformly distributed values.

By understanding their operational principles and applications, you will be equipped to select the most suitable technique for querying different datasets and scenarios, ultimately enhancing the efficiency of your applications.

Input Required

This code uses input(). Please provide values below: