Final code
Here is the full code of the main.cpp
file:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int binarySearch(vector<int> arr, int target) {
int low = 0;
int high = arr.size() - 1;
int mid;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
int main() {
vector<int> arr = {1, 3, 5, 7, 9, 11, 13, 15};
int target = 7;
int result = binarySearch(arr, target);
if (result == -1) {
cout << "Element not found!" << endl;
} else {
cout << "Element found at index " << result << endl;
}
return 0;
}