Binary search program in python - python coding - hackeradda
In this lesson on python coding, we will talk about one of the most famous, and fundamental algorithms in computer science binary search.
In this lesson on python coding, we will talk about one of the most famous, and fundamental algorithms in computer science binary search. Binary Search search algorithm is a very common question for python coding interviews. This article will help if you are preparing for a python coding interview, so let's try to write a simple python program to implement the binary search tree in python. These are some highlighted points about binary search algorithm
- Take greater advantage of the ordered list.
- The time complexity of the binary search
- Best-case performance O(1)
- Average performance O(log n)
first = 0
last = len(item_list)-1
found = False
while( first<=last and not found):
mid = (first + last)/2
if item_list[mid] == item :
found = True
if item < item_list[mid]:
last = mid - 1
first = mid + 1
Binary search recursive
def binary_search_recursive(list_of_numbers, number, start=0, end=None):
# The end of our search is initialized to None. First we set the end to the length of the sequence.
if end is None:
end = len(list_of_numbers) - 1
if start > end:
# This will happen if the list is empty of the number is not found in the list.
raise ValueError('Number not in list')
mid = (start + end) // 2 # This is the mid value of our binary search.
if number == list_of_numbers[mid]:
# We have found the number in our list. Let's return the index.
if number < list_of_numbers[mid]:
# Number lies in the lower half. So we call the function again changing the end value to 'mid - 1' Here we are entering the recursive mode.
return binary_search_recursive(list_of_numbers, number, start, mid - 1)
# number > list_of_numbers[mid]
# Number lies in the upper half. So we call the function again changing the start value to 'mid + 1' Here we are entering the recursive mode.
return binary_search_recursive(list_of_numbers, number, mid + 1, end)
Binary search with user input
high = k - 1
mid = (low + high)//2
elif key > mylist[mid]:
return binary_search(mylist,mid + 1,k ,key)
return binary_search(mylist,0,mid, key)
low = 0
k = int(input("Enter total amount of elements in k : "))
mylist = [int(input()) for x in range(k)]
key = int(input("Which element do we have to find: "))
The above python program will search for your given input in the sorted array and provides the boolean value if the given input is found in the given list or not.
Thank you for reading.
Currently I am working as a Full-stack developer and I have expertise with Python, Angular , PHP, Node JS, Laravel, Codeigniter and Front end.