Introduction
Binary Search is one of the most important algorithms in DSA and a favorite in technical interviews. Many learners know the formula but struggle to understand why it works.
In simple words, binary search is about cutting the search space into half again and again instead of checking every element.
Real-World Meaning of Binary Search
Imagine searching for a word in a dictionary:
You never start from the first page
You open the middle page
If your word comes earlier, you move left
Otherwise, you move right
This is exactly how binary search works.
What is Binary Search?
Binary Search is a searching technique used to find an element in a sorted array.
Important rule:
The array must be sorted
Binary search works by repeatedly dividing the array into two halves and deciding which half to continue searching in.
Before vs After Understanding
Linear Search (Before)
Array: [1, 3, 5, 7, 9]
Search: 7
Steps: 1 → 3 → 5 → 7
Binary Search (After)
Array: [1, 3, 5, 7, 9]
Search: 7
Steps: 5 → 7
Binary search drastically reduces the number of steps.
Why Linear Search is Not Efficient
Linear search checks:
One element at a time
From start to end
For large data, this becomes slow.
Interviewers expect you to optimize using binary search.
What Interviewers Are Actually Testing
When binary search is asked, interviewers check:
Do you understand sorted data requirement?
Can you calculate mid safely?
Can you avoid infinite loops?
Key Idea of Binary Search (Very Simple)
At every step:
Compare target with middle element
If equal → answer found
If smaller → go left
If larger → go right
Step-by-Step Logic
Set
lowto start of arraySet
highto end of arrayFind
midCompare
arr[mid]with targetReduce search space
Repeat until found or space is empty
Common Beginner Mistakes
Forgetting array must be sorted
Wrong mid calculation
Infinite loop due to incorrect conditions
One-Line Logic Before Code
Repeatedly cut the search space in half until the element is found.
Iterative Binary Search
C++ Code
int binarySearch(vector<int>& arr, int target) {
int low = 0, high = arr.size() - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target)
return mid;
else if (arr[mid] < target)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
Join the conversation! Your thoughts help the community grow.