-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtempCodeRunnerFile.c++
More file actions
35 lines (28 loc) · 907 Bytes
/
tempCodeRunnerFile.c++
File metadata and controls
35 lines (28 loc) · 907 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <vector>
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 bound
} else {
right = mid - 1; // Adjust the right bound
}
}
return -1; // Element not found
}
int main() {
std::vector<int> arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int target = 5;
int index = binarySearch(arr, target);
if (index != -1) {
std::cout << "Element found at index " << index << std::endl;
} else {
std::cout << "Element not found in the array" << std::endl;
}
return 0;
}