Introduction
This C++ program demonstrates the binary search algorithm, an efficient method for finding a target element in a sorted array of integers. Binary search repeatedly divides the search range in half, making it highly efficient with a time complexity of (O(\log n)). If the target element is found, the program returns its index; otherwise, it indicates that the element is not present in the array.
Code
#include <iostream>
using namespace std;
// Binary search function
int binarySearch(int arr[], int size, int target) {
int left = 0, right = size - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
// Check if the target is at mid
if (arr[mid] == target) {
return mid; // Element found at index mid
}
// If target is greater, ignore the left half
else if (arr[mid] < target) {
left = mid + 1;
}
// If target is smaller, ignore the right half
else {
right = mid - 1;
}
}
return -1; // Element not found
}
int main() {
int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
int size = sizeof(arr) / sizeof(arr[0]);
int target;
cout << "Enter the element to search for: ";
cin >> target;
int result = binarySearch(arr, size, target);
if (result != -1) {
cout << "Element found at index " << result << endl;
} else {
cout << "Element not present in the array." << endl;
}
return 0;
}
Output
Example 1:
Input:Enter the element to search for: 23
Output:Element found at index 5
Example 2:
Input:Enter the element to search for: 50
Output:Element not present in the array.
Conclusion
This program provides a clear and efficient way to search for an element in a sorted array using binary search. With its logarithmic time complexity, binary search is highly effective for large datasets, reducing the number of comparisons required to locate the target element. The program correctly identifies the position of an element or indicates if the element is absent, showcasing the power and simplicity of the binary search algorithm in C++.