DEV Community

Cover image for Understanding the Magic of Logarithms in Binary Search
Paula Fahmy
Paula Fahmy

Posted on

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

Top comments (0)