forked from pawanrajsingh2088/cpp-programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryss.cpp
More file actions
25 lines (23 loc) · 707 Bytes
/
binaryss.cpp
File metadata and controls
25 lines (23 loc) · 707 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
#include <iostream>
#include <vector>
#include <algorithm>
int binarySearch(const std::vector<int>& arr, int target) {
int left = 0, right = arr.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) return mid;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1; // Element not found
}
int main() {
std::vector<int> arr = {2, 3, 4, 10, 40};
int target = 10;
int result = binarySearch(arr, target);
if (result != -1)
std::cout << "Element found at index " << result << std::endl;
else
std::cout << "Element not found in array" << std::endl;
return 0;
}