Site icon DataFlair

Binary Search in Python (Recursive and Iterative)

Python course with 57 real-time projects - Learn Python

Searching for an element’s presence in a list is usually done using linear search and binary search. Linear search is time-consuming and memory expensive but is the simplest way to search for an element. On the other hand, Binary search is effective mainly due to the reduction of list dimension with each recursive function call or iteration. A practical implementation of binary search is autocompletion.

Python Binary Search Algorithm:

The objective of this project is to create a simple python program to implement binary search. It can be implemented in two ways: recursive (function calls) and iterative.

Project Prerequisites:

The project uses loops and functions to implement the search function. Hence good knowledge of python loops and function calls is sufficient to understand the code flow.

Download Binary Search Algorithm Python Code:

Please download the source code python binary search algorithm from the following link: Binary Search Python Code

Project File Structure:

Let’s have a look at the steps to build binary search python project:

1. Recursive approach

2. Iterative approach

Let us look at the implementation in detail.

1. Recursive approach

I. Function definition

#DataFlair Guide for Binary Search
#RECURSIVE FUNCTION CALL BASED APPROACH
#Function to search element in list
def binary_search(start,end,int_list,target):
  #Condition to check if element is not present 
  if start<=end:
     mid = (start+end) // 2
 
     #Check if mid element is the target element
     if int_list[mid] == target:
       return mid +1
 
     #If not, check if lesser than mid element
     #Change range to start to mid-1, since less than mid
     elif target < int_list[mid]:
       return binary_search(start,mid-1,int_list,target)
 
     #Check if lesser than mid element
     #Change range to mid+1 to end, since greater than mid
     elif target > int_list[mid]:
       return binary_search(mid+1,end,int_list,target)
  else:
     return -1

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

Code Explanation:

II. Read inputs and call function:

length = int(input("Enter length of list: "))
int_list = []
#Read elements of list
for i in range(length):
 element =  int(input("Enter element: "))
 int_list.append(element)
#Sort the list
int_list=sorted(int_list)
print(int_list)
#Read target element to be found
target = int(input("Enter target element: "))
position = binary_search(0,length-1,int_list,target)
if position == -1:
   print('Element not in list')
else:
   print("Element found at position: "+ str(position))

Code Explanation:

2. Iterative Approach:

Now, let’s discuss python binary search iterative approach:

I. Read inputs and sort the list:

#DataFlair Guide for Python Binary Search
#ITERATIVE APPROACH
#Read length of list from user
length = int(input("Enter length of list: "))
int_list = []
#Read elements of list
for i in range(length):
 element =  int(input("Enter element: "))
 int_list.append(element)
#Sort the list
int_list=sorted(int_list)
print(int_list)
#Read target element to be found
target = int(input("Enter target element: "))

Code explanation:

II. Loop for binary search

#Define variables
start = 0
end = length-1
position = -1
 
while(start<=end):
 mid = (start+end) // 2 
 if int_list[mid] == target:
   position = mid
   break
 #If not, check if lesser than mid element
 #Change range to start to mid-1, since less than mid
 elif target < int_list[mid]:
   end = mid-1
 #Check if lesser than mid element
 #Change range to mid+1 to end, since greater than mid
 elif target > int_list[mid]:
   start = mid+1
 
if position == -1:
   print('Element not in list')
else:
   print("Element found at position: "+ str(position+1))

Code Explanation:

Binary Search Python Output:

Summary

We created a simple Binary Search Algorithm in Python. The python project covers both: an iterative approach using loops and recursive function calls using function.

Exit mobile version