Table of Contents
Python program for binary search
The binary search algorithm for a sorted sequence produced a slight improvement over the linear search with an unsorted sequence, but both have a linear time complexity in the worst case.
It is used to search the number in array.
Following program will help university students and beginners to understand the concepts and working of Binary search.
""" Author : ITVoyagers (itvoyagers.in) Date :5th December 2019 Description : Python program for binary search """ def binarysearch(list1, value): first = 0 last = len(list1)-1 found = False while first<=last and not found: mid = (first + last)//2 if list1[mid] == value: found = True else: if value < list1[mid]: last = mid-1 else: first = mid+1 return found
Output:
>>> binarysearch([2,4,6,8,10],10) True >>> binarysearch([2,4,6,8,10],11) False >>>
Note : Please note that above program is compatible with Python 3 or higher version.
Please check out other practical related to Data structures
1 thought on “Python program for binary search”