0
0
DSA Goprogramming~3 mins

Why Binary Search Recursive Approach in DSA Go?

Choose your learning style9 modes available
The Big Idea

What if you could find a needle in a haystack by looking at only a few spots?

The Scenario

Imagine you have a huge phone book with thousands of names sorted alphabetically. You want to find one name, but you start from the first page and check every single name one by one.

The Problem

This manual way takes a lot of time because you might have to look through many pages before finding the name. It is slow and tiring, and you can easily lose your place or make mistakes.

The Solution

Binary search uses a smart trick: it looks at the middle page first, then decides if the name is before or after that page. It repeats this by cutting the search area in half each time, quickly zooming in on the right spot.

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

This approach lets you find items in huge sorted lists very fast, saving time and effort.

Real Life Example

When you search for a word in a dictionary app, it uses binary search to quickly jump to the right page instead of scrolling through every word.

Key Takeaways

Manual search checks items one by one, which is slow.

Binary search cuts the search area in half each step, speeding up the process.

Recursive binary search repeats this halving until it finds the target or ends.