o1-mini-2024-09-12· openai
from WildChat-4.8M
write a binary search c++ implementation
- User
write a binary search c++ implementation
- Assistant
Certainly! Below is a complete C++ implementation of the binary search algorithm. This implementation includes:
- Binary Search Function: An iterative approach to perform binary search on a sorted array.
- Main Function: Demonstrates how to use the binary search function with a sample array.
- Comments: Explanation of each part of the code for better understanding.
Binary Search in C++
cpp#include <iostream> #include <vector> #include <algorithm> // For sorting the array (if needed) // Function to perform binary search // Returns the index of the target if found, otherwise returns -1 int binarySearch(const std::vector<int>& arr, int target) { int left = 0; // Initialize left boundary int right = arr.size() - 1; // Initialize right boundary while (left <= right) { int mid = left + (right - left) / 2; // Prevents potential overflow // Check if target is present at mid if (arr[mid] == target) { return 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; } } // Target wasn't found in the array return -1; } int main() { // Sample array (must be sorted for binary search) std::vector<int> data = {2, 3, 4, 10, 15, 18, 21, 28, 35, 42}; // If the array is not sorted, uncomment the next line to sort it // std::sort(data.begin(), data.end()); int target = 15; // Element to search for int result = binarySearch(data, target); if (result != -1) { std::cout << "Element " << target << " found at index " << result << ".\n"; } else { std::cout << "Element " << target << " not found in the array.\n"; } return 0; }