  # In this lesson on python coding, we will talk about one of the most famous, and fundamental algorithms in computer science binary search.  Harendra Verma

2 years ago | 2 min read

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)

Binary Search

``def binary_search(item_list,item):	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		else:			if item < item_list[mid]:				last = mid - 1			else:				first = mid + 1		return found	print binary_search([1,2,3,5,8],6)print binary_search([1,2,3,5,8],5)``

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.        return mid    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)print binary_search_recursive([1,2,3,5,8],6)print binary_search_recursive([1,2,3,5,8],5)``

Binary search with user input

``def binary_search(mylist,low,k,key):    high = k - 1    mid = (low + high)//2        if mylist[mid]==key:        return mid    elif key > mylist[mid]:        return binary_search(mylist,mid + 1,k ,key)    else:        return binary_search(mylist,0,mid, key)low = 0k = 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: "))print(binary_search(mylist,low,k,key))``

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.

Upvote  Created by

Harendra Verma

Currently I am working as a Full-stack developer and I have expertise with Python, Angular , PHP, Node JS, Laravel, Codeigniter and Front end. Post

Upvote

Downvote

Comment

Bookmark

Share

Related Articles