0
0
DSA C++programming~3 mins

Why Binary Search Iterative Approach in DSA C++?

Choose your learning style9 modes available
The Big Idea

What if you could find anything in a huge list in just a few steps?

The Scenario

Imagine you have a thick phone book with thousands of names sorted alphabetically. You want to find a friend's phone number. If you start from the first page and check every name one by one, it will take a very long time.

The Problem

Searching one by one is slow and tiring. It wastes time because you check many names unnecessarily. Also, it's easy to lose track or make mistakes when the list is huge.

The Solution

Binary search helps by quickly cutting the list in half each time. Instead of checking every name, you jump to the middle, decide which half your friend's name is in, and repeat. This way, you find the name much faster and with fewer checks.

Before vs After
Before
for (int i = 0; i < size; i++) {
  if (array[i] == target) {
    return i;
  }
}
return -1;
After
int left = 0, right = size - 1;
while (left <= right) {
  int mid = left + (right - left) / 2;
  if (array[mid] == target) return mid;
  else if (array[mid] < target) left = mid + 1;
  else right = mid - 1;
}
return -1;
What It Enables

Binary search enables lightning-fast searching in sorted lists, saving time and effort.

Real Life Example

When you search for a word in a dictionary app, it uses binary search to quickly find the word instead of checking every entry.

Key Takeaways

Manual search checks every item, which is slow.

Binary search cuts the search space in half each step.

This makes finding items in sorted lists much faster.