-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathbinarysearch.cpp
More file actions
37 lines (31 loc) · 893 Bytes
/
Copy pathbinarysearch.cpp
File metadata and controls
37 lines (31 loc) · 893 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
36
37
#include <bits/stdc++.h>
using namespace std;
/*
🧠 Binary Search Algorithm
- Works on sorted arrays.
- Repeatedly divides the search interval in half.
- Time Complexity: O(log n)
*/
int binarySearch(vector<int> &arr, int target) {
int low = 0, high = arr.size() - 1;
while (low <= high) {
int mid = low + (high - low) / 2; // prevent overflow
if (arr[mid] == target)
//check
return mid; // target found
else if (arr[mid] < target)
low = mid + 1; // search right half
else
high = mid - 1; // search left half
}
return -1; // target not found
}
int main() {
vector<int> arr = {2, 4, 6, 8, 10, 12, 14};
int target = 10;
int result = binarySearch(arr, target);
if (result != -1)
cout << "Element found at index " << result;
else
cout << "Element not found";
}