What if you could find anything in a huge list in just a few steps?
Why Binary Search Iterative Approach in DSA C++?
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.
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.
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.
for (int i = 0; i < size; i++) { if (array[i] == target) { return i; } } return -1;
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;
Binary search enables lightning-fast searching in sorted lists, saving time and effort.
When you search for a word in a dictionary app, it uses binary search to quickly find the word instead of checking every entry.
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.