Python Program to Implement Binary Search without Recursion


When it is required to implement binary search without using dictionary, a method can be defined that checks the first and last index of the list, and gets the middle value of the list.

It is then compared to the value that needs to be checked for. If it is found, the value is returned. Else, -1 is returned.

It is important to remember that binary search works on sorted elements only, either ascending or descending order.

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

Below is a demonstration for the same −

Example

Live Demo

def binary_search(my_list, elem):
   low = 0
   high = len(my_list) - 1
   mid = 0
   while low <= high:
      mid = (high + low) // 2
      if my_list[mid] < elem:
         low = mid + 1
      elif my_list[mid] > elem:
         high = mid - 1
      else:
         return mid
   return -1

my_list = [ 1, 9, 11, 21, 34, 54, 67, 90 ]
elem_to_search = 1
print("The list is")
print(my_list)

my_result = binary_search(my_list, elem_to_search)

if my_result != -1:
   print("Element found at index ", str(my_result))
else:
   print("Element not found!")

Output

The list is
[1, 9, 11, 21, 34, 54, 67, 90]
Element found at index  0

Explanation

  • A method named 'binary_search' is defined that takes the list and the element to be searched for, as parameters.
  • A variable low is assigned to 0 and variable mid is assigned to 0.
  • The variable high is assigned the length of list-1.
  • Bitwise floor division is performed to get the value for 'mid' variable, only if the value 'low' is less than or equal to 'high'
  • First the element is searched from low to mid index, if the value is less than value present at mid index.
  • Else the element is searched from mid to high index, if the value is greater than mid and less than high.
  • Now, a list is defined.
  • The method is called by passing the above list as parameter.
  • This operation's data is stored in a variable.
  • This variable is the output that is displayed on the console.

Updated on: 13-Mar-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements