Understanding the Magic of Logarithms in Binary Search

paulafahmy

Paula Fahmy

Posted on March 9, 2024

Understanding the Magic of Logarithms in Binary Search

Hey community! πŸ‘‹ Today, let's demystify the magic behind the efficiency of algorithms like binary search. Ever wondered why we say binary search has a time complexity of O(log N)?

Let's break it down in simple terms.

Imagine you have a row of boxes, and you want to find a particular item in one of them. Now, let's use binary search to make this process super efficient.

Step 1: Start with 16 boxes.

πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦
Enter fullscreen mode Exit fullscreen mode

Step 2: Each time, divide the number of remaining boxes by 2.

πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦   πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦
Enter fullscreen mode Exit fullscreen mode

Step 3: Repeat until you have only one box left.

        πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦   πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦πŸ“¦
Step 1:           πŸ“¦πŸ“¦πŸ“¦πŸ“¦   πŸ“¦πŸ“¦πŸ“¦πŸ“¦
Step 2:                πŸ“¦πŸ“¦   πŸ“¦πŸ“¦
Step 3:                   πŸ“¦   πŸ“¦
Step 4:                      πŸ“¦
Enter fullscreen mode Exit fullscreen mode

Here's the cool part: The number of steps it takes to go from 16 boxes to 1 box is surprisingly related to the concept of logarithms!

Mathematically, we can represent this as:
img

In the case of our 16 boxes example, it becomes:
img

Now, let's use logarithms to solve for the number of steps. Taking the base-2 logarithm of both sides gives us:
img

So, in this example:
img

Steps in this case equals to 4..

Voila! The number of steps it takes to find an item in our binary search is logarithmic with respect to the number of elements (N) we started with. Hence, the time complexity of binary search is O(log N).

Understanding this concept can help us appreciate the efficiency of algorithms that reduce the search space by half in each step.

Happy searching! πŸ”πŸ’‘ #AlgorithmMagic #BinarySearch #LogarithmsExplained

πŸ’– πŸ’ͺ πŸ™… 🚩
paulafahmy
Paula Fahmy

Posted on March 9, 2024

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

Sign up to receive the latest update from our blog.

Related