Site icon WP Pluginsify

Binary Search Algorithm Explained With Examples

Imagine you are looking for a name in a long, sorted list. You could start from the top and check one by one. That works. But it is slow. There is a smarter way. It is called the Binary Search Algorithm. It cuts the problem in half again and again. Fast. Clean. Powerful.

TLDR: Binary search is a fast way to find an item in a sorted list. It works by checking the middle element and cutting the search space in half each time. This makes it much faster than checking every item one by one. But it only works on sorted data.

What Is Binary Search?

Binary search is a search algorithm. It finds the position of a target value inside a sorted array or list.

The key word here is sorted.

If the list is not sorted, binary search will not work correctly.

Here is the big idea:

Each step throws away half of the remaining elements.

That is why it is called binary. Two halves. Every time.

Why Is It So Fast?

Let us compare.

Imagine a list of 1,000 numbers.

Linear search may check up to 1,000 elements.

Binary search?

It checks at most about 10 elements.

Yes. Just 10.

Because:

Each step cuts the list in half.

This is called O(log n) time complexity.

Do not let that scare you. It just means “very fast for big lists.”

Let’s See a Simple Example

Suppose we have this sorted array:

[3, 8, 12, 20, 27, 31, 45, 50, 62]

We want to find 27.

Image not found in postmeta

Step 1: Look at the Middle

The middle element is 27.

We got lucky.

It matches the target.

We are done in one step.

But that was too easy.

Let’s Try a Harder Example

Same array:

[3, 8, 12, 20, 27, 31, 45, 50, 62]

Now we search for 50.

Step 1: Check the Middle

Middle element is 27.

50 is greater than 27.

So we ignore the left half.

New search space:

[31, 45, 50, 62]

Step 2: Check New Middle

Middle element is 45.

50 is greater than 45.

Ignore the left half again.

New search space:

[50, 62]

Step 3: Check Middle Again

Middle element is 50.

Match found.

Only three steps.

That is the magic.

Visualizing the Halves

Think of it like a phone book.

If you want to find “Smith,” you do not start at page one.

You open near the middle.

If the names there start with “M,” you move right.

If they start with “T,” you move left.

You keep cutting the book in half.

This is binary search in real life.

Binary Search in Code (Simple Version)

Here is a simple version in Python:

def binary_search(arr, target):
    left = 0
    right = len(arr) - 1

    while left <= right:
        mid = (left + right) // 2

        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1

    return -1

Let us break it down.

Simple logic. Big impact.

Important Rule: The Array Must Be Sorted

This is critical.

If the array is not sorted, binary search breaks.

Example:

[12, 3, 50, 8, 27]

This is not sorted.

If you apply binary search here, results will be wrong.

Always sort first.

Sorting takes time. But after that, searching becomes extremely fast.

Recursive Version

Binary search can also be written using recursion.

def binary_search_recursive(arr, target, left, right):
    if left > right:
        return -1

    mid = (left + right) // 2

    if arr[mid] == target:
        return mid
    elif arr[mid] < target:
        return binary_search_recursive(arr, target, mid + 1, right)
    else:
        return binary_search_recursive(arr, target, left, mid - 1)

This version calls itself.

Each call reduces the problem size.

Same logic. Different style.

When Should You Use Binary Search?

Use binary search when:

Common use cases:

Binary Search in a Guessing Game

Imagine a game.

You must guess a number between 1 and 100.

You guess 50.

If the answer is higher, you guess 75.

If lower, you guess 25.

You continue halving the range.

You will always find the correct number in at most 7 guesses.

That is binary search thinking.

Common Mistakes

Even though binary search is simple, beginners make mistakes.

Be careful with boundaries.

The condition left <= right is important.

Time Complexity Explained Simply

Let us say you have:

See the pattern?

Even if the data becomes huge, steps increase slowly.

That is the beauty of logarithms.

Binary Search vs Linear Search

Feature Linear Search Binary Search
Data must be sorted No Yes
Worst-case time O(n) O(log n)
Best for small lists Yes Okay
Best for large lists No Yes

If the list is tiny, linear search is fine.

If the list is huge, binary search wins.

Final Thoughts

Binary search is one of the most important algorithms in computer science.

It teaches a powerful lesson.

Do not check everything.

Be smart.

Divide the problem.

Remove half the possibilities.

Repeat.

That idea appears everywhere in programming.

In searching.

In optimization problems.

In machine learning.

In game development.

Once you understand binary search, you start to see it everywhere.

And the best part?

It is simple.

Just remember:

That is it.

You now understand binary search.

Fast. Elegant. Powerful.

Exit mobile version