Write a simple binary search code in c++.
- User
Write a simple binary search code in c++.
Assistant
Here's a simple implementation of binary search in C++:
#include <iostream> #include <vector> using namespace std; int binarySearch(const vector<int>& arr, int target) { int left = 0; int right = arr.size() - 1; while (left <= right) { int mid = left + (right - left) / 2; // Prevents overflow if (arr[mid] == target) { return mid; // Target found } else if (arr[mid] < target) { left = mid + 1; // Search right half } else { right = mid - 1; // Search left half } } return -1; // Target not found } int main() { vector<int> sortedArray = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91}; int target = 23; int result = binarySearch(sortedArray, target); if (result != -1) { cout << "Element found at index: " << result << endl; } else { cout << "Element not found in the array" << endl; } return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.