Binary Search Explained

easewithtuts

V Sai Harsha

Posted on September 22, 2023

Binary Search Explained

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

Binary Search

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!

💖 💪 🙅 🚩
easewithtuts
V Sai Harsha

Posted on September 22, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Binary Search Explained
computerscience Binary Search Explained

September 22, 2023

Extreme JavaScript Type Coercion
javascript Extreme JavaScript Type Coercion

February 14, 2023

Recursion : Linear recursion and Tail recursion
computerscience Recursion : Linear recursion and Tail recursion

October 13, 2021

Optimize Fibonacci with Dynamic Programming
computerscience Optimize Fibonacci with Dynamic Programming

September 20, 2021

Hash Table explained like I'm 5
computerscience Hash Table explained like I'm 5

April 30, 2021