Binary Search Algorithm in Python

Photo by Chris Ried on Unsplash

Binary Search Algorithm in Python

Binary search is a popular algorithm for finding the element’s position in a sorted array. In this article, we will learn how the binary search algorithm works with some examples in Python.

In this approach, the value is always searched in the middle portion of the array. Since the binary search can be implemented only on a sorted array so if the values of an array are unsorted, we need to sort them first.

The binary algorithm is also known as half-interval and uses the divide-and-conquer algorithm; like all divide-and-conquer algorithms- binary search divides the given array into two small subarrays based on the middle index; instead of working on two subarrays. The algorithm will discard the one subarray and continues working on the other subarray.

How binary search algorithm works.

  • Step1: It begins with comparing the middle element of the whole array with the value.
  • Step2: if the value is equal to the middle element return the index of the middle element.
  • Step3: Or If the value is less than the middle element search continues in the lower half of the array.
  • Step4: Or If the value is greater than the middle element search continues in the upper half of the array.
  • Step5: Repeat the steps from 2 until the value is not found or the interval is empty. If the search ends empty interval, the value is not in the array.

Python Code for binary search using Recursive method

# Python program to search element index in,
# the given array using a binary search algorithm.

## Recursive method
def binary_search(value, arr):

    if len(arr) == 0:
        return None

    if len(arr) == 1:
        if arr[0] == value:
            return "0"
    else:
        mid_index = len(arr) // 2
        mid_value = arr[mid_index]

        if mid_value == value:
            return mid_index
        elif mid_value > value:
            return binary_search(value, arr[:mid_index])
        elif mid_value < value:
            return binary_search(value, arr[mid_index:])
        else:
            return None

if __name__ == '__main__':

    arr= [1, 2, 3, 4, 5, 6, 8]  # given sorted array list
    value = 4 # value to be searched.
    result = binary_search(value, arr)

    if result:
        print(f"The value {value} is present at index {result}.")
    else:
        print(f"The value {value} is not present in the array.")

## Output: The value 4 is present at index 3.

Linear search is another searching algorithm that compares each element of an array with a value(for example, using the for loop) which is more time-consuming than the binary search since binary search reduces the search space(i.e array size) to half at each step. Initially, search space is the entire array; binary search redefines the search space at every step of the algorithm by using the property of the sorted array by comparing mid-value in the search space to value.

Of course, there are other search algorithms present that are much faster but more complex than binary search. I hope this article helps you to understand how the binary search algorithm works and how you can implement it in Python programming language.

Thank you for reading. See you in my next article. Until next time keep learning!

Did you find this article valuable?

Support Madhuri's blog by becoming a sponsor. Any amount is appreciated!