Binary Search (Iterative)
Binary Search Algorithm in C++ (Iterative Implementation)
BeginnerTopic: Sorting & Searching Programs
C++ Binary Search (Iterative) Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
using namespace std;
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
}
int main() {
int arr[] = {11, 12, 22, 25, 34, 64, 90};
int n = sizeof(arr) / sizeof(arr[0]);
int key;
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
cout << "Enter element to search: ";
cin >> key;
int result = binarySearch(arr, n, key);
if (result != -1) {
cout << "Element found at index: " << result << endl;
} else {
cout << "Element not found in array" << endl;
}
return 0;
}Output
Sorted array: 11 12 22 25 34 64 90 Enter element to search: 25 Element found at index: 3
Understanding Binary Search (Iterative)
Binary Search is a divide-and-conquer algorithm that searches a sorted array by repeatedly dividing the search interval in half. Time Complexity: O(log n). Space Complexity: O(1). It requires the array to be sorted and is much faster than linear search for large datasets. This is the iterative implementation.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.