Binary Search (Iterative) in C++
Binary Search Algorithm in C++ (Iterative Implementation).
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}
Output
Sorted array: 11 12 22 25 34 64 90 Enter element to search: 25 Element found at index: 3
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
This header provides:
1#include <iostream>
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) {
}
if (arr[mid] < key) {
left = mid + 1; // Search right half
} else {
right = mid - 1; // Search left half
}
}
return -1; // Not found
}
1return mid; // Found at index mid
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.