Binary Search (Iterative) in C++
Find a value in a sorted array with iterative binary search in C++, halving the range each step with left, right, and mid. Explains why the input must be sorted.
1#include <iostream>2using namespace std;34int binarySearch(int arr[], int n, int key) {5 int left = 0;6 int right = n - 1;78 while (left <= right) {9 int mid = left + (right - left) / 2;1011 if (arr[mid] == key) {12 return mid; // Found at index mid13 }1415 if (arr[mid] < key) {16 left = mid + 1; // Search right half17 } else {18 right = mid - 1; // Search left half19 }20 }2122 return -1; // Not found23}2425int main() {26 int arr[] = {11, 12, 22, 25, 34, 64, 90};27 int n = sizeof(arr) / sizeof(arr[0]);28 int key;2930 cout << "Sorted array: ";31 for (int i = 0; i < n; i++) {32 cout << arr[i] << " ";33 }34 cout << endl;3536 cout << "Enter element to search: ";37 cin >> key;3839 int result = binarySearch(arr, n, key);4041 if (result != -1) {42 cout << "Element found at index: " << result << endl;43 } else {44 cout << "Element not found in array" << endl;45 }4647 return 0;48}
Sample Output
Element found at index: 3
25 found on the first probe.
In this one
- Why binary search needs sorted data
- How left, right, and mid shrink the search range
- Why mid = left + (right - left) / 2 avoids overflow
- Why it takes O(log n) steps
How it works
- 1
left = 0, right = 6.
- 2
mid = 3, arr[3] = 25 equals key.
- 3
Return 3.
Searching for 64
Range after each step.
- 1.left 0, right 6, mid 3 (25 < 64) → left 4
- 2.left 4, right 6, mid 5 (64) → found
Edge cases
Unsorted input
Search 3 in {5, 1, 3, 2}.
mid lands on 1, the code moves right and may miss 3. The answer is unreliable on unsorted arrays.
Condition left < right
Drop the = in left <= right.
When the range shrinks to one element the loop stops without checking it, so some keys are reported missing.
What's going on
The program searches for an element in a sorted array using Binary Search (iterative version). For example:
Binary Search eliminates half of the remaining elements in each step, making it extremely efficient.
Header File Used
#include <iostream>
This header provides:
Understanding Binary Search
Algorithm Concept:
Visual Example:
Array: [11, 12, 22, 25, 34, 64, 90]
Search for: 25
Step 1: left=0, right=6, mid=3
Example (searching for 34):
Step 1: left=0, right=6, mid=3
Step 2: left=4, right=6, mid=5
Step 3: left=4, right=4, mid=4
Function: binarySearch()
int binarySearch(int arr[], int n, int key) {
int left = 0;
int right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == key) {
return mid; // Found at index mid
}
if (arr[mid] < key) {
left = mid + 1; // Search right half
} else {
right = mid - 1; // Search left half
}
}
return -1; // Not found
}
How it works:
Step-by-Step Algorithm
Step 1: Initialize Interval
Step 2: Calculate Middle
Step 3: Compare
Step 4: Repeat
Understanding Mid Calculation
Why left + (right - left) / 2?
Example:
Time and Space Complexity
Time Complexity: O(log n)
Space Complexity: O(1)
When to Use Binary Search
Best For:
Not Recommended For:
Important Considerations
Array Must Be Sorted:
Loop Condition:
Index Updates:
Advantages Over Linear Search
Performance:
Efficiency:
return 0;
This ends the program successfully.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Max steps for 1,000,000 elements?
Pick an answer to check it.
Question 2
If arr[mid] < key, the next range is:
Pick an answer to check it.
Questions people ask
Iterative or recursive?
Both are O(log n). The loop uses constant stack space.
Library version?
std::binary_search returns true or false; lower_bound gives the position.
Duplicates?
It returns some matching index, not necessarily the first.