Python: Implement Binary Search Algorithm – A Step Guide

In this tutorial, we will implement binary search using python script.

1. Creae a sorted list, which contains some numbers we plan to search.

data_list = [12, 25, 43, 59, 61, 78, 92] # 7

There are 7 numbers in data_list

2. Set value you want to search.

value= 78

3. Implement binary search

low=0
high=len(data_list)
while(low<=high):
    mid=int((low+high)/2)

    if(data_list[mid]==value):
        print("Element found at ",mid)
        break
    elif(data_list[mid]<value):
        low=mid+1
    elif(data_list[mid]>value):
        high=mid-1
if(low>high):
    print("Element not found")

Run this code, you will get the result.

Element found at  5

If value = 32, you will get the result:

Element not found