-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path11th_binary_search.cpp
More file actions
54 lines (43 loc) · 1.17 KB
/
Copy path11th_binary_search.cpp
File metadata and controls
54 lines (43 loc) · 1.17 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <vector>
using namespace std;
//linear search == O(n)
// binary search == O(log n) -- must be sorted array
int binarySearch(vector<int> arr, int tar){ //iterative
int st = 0,end = arr.size()-1;
while(st <= end){
int mid = st + (end-st)/2;
if(tar > arr[mid]){
st = mid + 1;
}else if(tar < arr[mid]){
end = mid - 1;
}else{
return mid;
}
}
return -1;
}
// recursion code
;
int recBinarySearch(vector<int> arr, int tar, int st , int end){
if(st <= end){
int mid = st + (end-st)/ 2;
if(tar > arr[mid]){ // 2nd half
return recBinarySearch(arr, tar, mid+1,end);
}else if(tar < arr [mid]){ // 1st half
return recBinarySearch(arr, tar, st, mid-1);
}else { // mid => ans
return mid;
}
}
return -1;
}
int main(){
vector< int > arr1 = {-1,0,3,4,5,9,12}; // odd
int tar1 = 40;
//cout << binarySearch(arr1, tar1) << endl;
vector <int> arr2 = {-1,0,3,4,9,12}; //even
int tar2 = 0;
cout << binarySearch(arr2, tar2) << endl;
return 0;
}