Advertisement
Programmin-in-Python

Implementing Binary Search in Python

Jan 21st, 2021
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.81 KB | None | 0 0
  1. def binary_search(arr, elem):
  2.     start, end = 0, len(arr)-1
  3.  
  4.     while start <= end:
  5.         mid = (start+end)//2
  6.  
  7.         if elem == arr[mid]:
  8.             return mid
  9.         elif elem < arr[mid]:
  10.             end = mid-1
  11.         else:
  12.             start = mid+1
  13.  
  14.     else:
  15.         return False
  16.  
  17. arr, choice = [], "y"
  18. print("The List is now Empty...\nPlease Enter some elements into it...\n")
  19.  
  20. while choice.lower() == "y":
  21.     elem = int(input("Enter the INTEGER element to be inserted : "))
  22.     arr.append(elem)
  23.     print("\nNow the List contains : ", arr)
  24.  
  25.     choice = input("\nDo You Want to insert more elements into it? (Y/[n]) : ")
  26.  
  27. find = int(input("Enter the Element to be found : "))
  28. pos = binary_search(arr, find)
  29.  
  30. if bool(pos):
  31.     print(f"The element is found at {pos+1} position")
  32. else:
  33.     raise ValueError("Oops!!! The Given Element is NOT PRESENT in the given list")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement