Binary Search in Python
Basically, binary search is searching algorithm used to search specific elements in the sorted list of elements. Binary search is more efficient than the linear search because its worst time complexity is O(log n) whereas that of linear search is O(n) but it has same best case time complexity of O(1).
How does the binary search algorithm works?
In the binary search algorithm, the input to the binary search algorithm is a sorted list of elements and the search element itself. Then we find the mid position value of the sorted list of elements and compare the value with the search elements. If it is a match then the element is found. If not we compare whether the search element is greater than or less than the mid value. If the search element is less than the mid value we search in the left side of the list from mid value. If the search element is greater than the mid value we search on the right side of the list from the mid value. We continue the same process until the search element is found. If it is not present in the list after the values are been compared then we conclude that the search element is not present in the list.
The code for binary search in python.
The code shown below is the binary search algorithm written in python 3. The code gives you how the binary search algorithm works but remember the code is not optimized one still then it is a fully working code.
The binary search algorithm is implemented using the concept of recursion function. If you are not familiar with recursion function you can refer to my previous post by clicking on this link Recursion Function in Python 3.
The binary search algorithm is implemented using the concept of recursion function. If you are not familiar with recursion function you can refer to my previous post by clicking on this link Recursion Function in Python 3.