What if you could find a needle in a haystack by looking at only a few spots?
Why Binary Search Recursive Approach in DSA Go?
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.
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.
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.
for i := 0; i < len(arr); i++ { if arr[i] == target { return i } } return -1
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)
}
}This approach lets you find items in huge sorted lists very fast, saving time and effort.
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.
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.