0
0
DSA Goprogramming~3 mins

Why Binary Search and What Sorted Order Gives You in DSA Go - The Real Reason

Choose your learning style9 modes available
The Big Idea

What if you could find anything in a huge list in just a few steps instead of searching forever?

The Scenario

Imagine you have a huge phone book with thousands of names, and you want to find one person's phone number.

If you look at each name one by one from the start, it will take a very long time.

The Problem

Searching one by one is slow and tiring.

It's easy to lose your place or make mistakes.

It wastes a lot of time, especially when the list is very long.

The Solution

Binary search uses the fact that the list is sorted to jump quickly to the middle and decide which half to search next.

This way, it cuts the search area in half each time, finding the item very fast.

Before vs After
Before
for i := 0; i < len(list); i++ {
    if list[i] == target {
        return i
    }
}
return -1
After
low, high := 0, len(list)-1
for low <= high {
    mid := (low + high) / 2
    if list[mid] == target {
        return mid
    } else if list[mid] < target {
        low = mid + 1
    } else {
        high = mid - 1
    }
}
return -1
What It Enables

It lets you find items in huge sorted lists very quickly, saving time and effort.

Real Life Example

When you search for a word in a dictionary, you don't read every word; you jump to the middle, then left or right, quickly finding the word.

Key Takeaways

Manual search checks every item, which is slow for big lists.

Binary search uses sorted order to cut search time drastically.

Sorted order is key to making binary search work efficiently.