
435 views
Binary Search in C++
Binary search is an efficient algorithm used to search for a specific element in a sorted array. Here’s an example of how to implement binary search in C++:
C++
#include <iostream>
#include <vector>
// Binary search function
int binarySearch(const std::vector<int>& arr, int target) {
int left = 0;
int right = arr.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid; // Element found; return its index
} else if (arr[mid] < target) {
left = mid + 1; // Adjust the left boundary
} else {
right = mid - 1; // Adjust the right boundary
}
}
return -1; // Element not found
}
int main() {
std::vector<int> sortedArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int target = 7;
int result = binarySearch(sortedArray, target);
if (result != -1) {
std::cout << "Element " << target << " found at index " << result << std::endl;
} else {
std::cout << "Element " << target << " not found in the array." << std::endl;
}
return 0;
}In this code:
- We define a
binarySearchfunction that takes a sorted vectorarrand a target valuetargetas parameters. - We initialize two pointers,
leftandright, which represent the current search range. Initially,leftis set to the beginning of the array (index 0), andrightis set to the end of the array (indexarr.size() - 1). - Inside the
whileloop, we calculate the middle index (mid) of the current search range. - We compare the element at the middle index with the target value:
- If they are equal, we return the index of the element (indicating that the element has been found).
- If the element at the middle index is less than the target, we adjust the
leftpointer tomid + 1to search the right half of the current range. - If the element at the middle index is greater than the target, we adjust the
rightpointer tomid - 1to search the left half of the current range.
- We repeat this process until
leftis less than or equal toright. If the loop exits without finding the target element, we return-1to indicate that the element is not in the array. - In the
mainfunction, we create a sorted vectorsortedArrayand specify the target value to search for. - We call the
binarySearchfunction and display the result, indicating whether the target element was found and at which index.
This binary search algorithm has a time complexity of O(log n), making it efficient for searching in large sorted datasets.