Binary Search Explained
V Sai Harsha
Posted on September 22, 2023
Introduction
Binary Search is a searching algorithm where the sorted array is repeatedly split into two halves to find the item. It is implemented in two ways:
- We can use a While loop
- Use Recursion.
Explaination
Here, we can see our sorted array. Which is:
[1,2,3,4,5,6,7,8]
0 1 2 3 4 5 6 7 - Indices of the items
We have Four Values.
- Start (0)
- End (length - 1 E.g. 8 - 1 = 7)
- Mid ((Start + End) // 2) - Floor Division
- Target (in our example: 6)
So, if the value of middle is equal to the target, then return the middle index.
If the target is greater than the middle index, then, change the start index to 1 more than the middle index. i.e. mid + 1.
Else, change the end index to 1 less than the middle index.
From our example, We can see that in the starting array. The target is on the right side. So, the start index is 1 more than the middle index.
We repeat the process of modifying either the start or end index and check our middle index is equal to the target until the start index is greater than end index, if it is that condition. Then, We aren't able to search our item in our array.
Conclusion
I hope you understand this explanation of Binary Search Algorithm. Happy Coding!
Posted on September 22, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.