In this article, we will have a short look at Binary Search In Python. Binary Search is a part of algorithms in Computer Science. Binary means two like 0s and 1s are a good example of the binary system in Computer Science.
In Binary Search, we take some sorted elements inside an array or List.
Then we create three parameters, first, middle, and last.
Now, we create a loop and we runs it untill we don’t find the element we are searching for.
Then we first check the middle element of the array with the element we are searching.
Now, three conditions applies here.
- Elements matches
- The middle element is less than the element we are searching for
- The middle element is greater than the element we are searching for
Now, if the element matches then we exits the loop successfully.
Else if the middle element is less than the element we are searching for then we assign the first element the element which is one greater than the middle element and search for the element in the same way as we were doing till now.
first = middle + 1
The case reverses when it comes to the third point.
If the middle element is greater than the element we are searching for then we assign the element which is one less than the middle element as the last element and search for the element in the same way as we were doing till now.
last = middle – 1
Code
myList = [12, 23, 34, 45, 56, 67] mysearch = 23 def binaryFun(myList, mysearch): first = 0 last = len(myList) - 1 mid = 0 while first<=last: mid = (first + last)//2 if myList[mid] == mysearch: return mid elif mysearch > myList[mid]: first = mid + 1 elif mysearch < myList[mid]: last = mid - 1 return "not found" result = binaryFun(myList, mysearch) print(result)
Output
1
Also Read:
Introduction to Searching Algorithms: Linear Search Algorithm
Selection Sort Algorithm In Data Structures and Algorithms using Python
Bubble Sort Algorithm In Data Structures & Algorithms using Python
Merge Sort Algorithm in Python
Quick Sort algorithm in data structures and algorithms using Python
Insertion Sort Algorithm in Data Structures using Python
Heap Sort Algorithm|Heap Data Structure