-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathl33BinarySearch.cpp
More file actions
44 lines (43 loc) · 903 Bytes
/
l33BinarySearch.cpp
File metadata and controls
44 lines (43 loc) · 903 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
38
39
40
41
42
43
44
#include<iostream>
using namespace std;
void print(int arr[], int s, int e){
for(int i = s; i<=e; i++){
cout<<arr[i]<<" ";
}cout<<endl;
}
bool LinearSearch(int arr[], int size, int k){
// base case
if(size==0){
return false;
}
if(arr[0]==k){
return true;
}
else{
bool remainingPart = LinearSearch(arr+1, size-1, k);
return remainingPart;
}
}
int binarySearch(int arr[], int s, int e, int k){
//base case
print(arr,s, e);
if(s>e){
return false;
}
int mid = s+ (e-s)/2;
if(arr[mid] == k){
return mid;
}
if(arr[mid]<k){
binarySearch(arr, mid+1, e, k);
}
else{
binarySearch(arr, s, mid-1, k);
}
}
int main(){
int arr[6] = {2, 4, 6, 10,14, 16};
int size = 6;
int key = 10;
cout<<"Present or not "<<binarySearch(arr, 0, 5, key)<<endl;
}