-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day-050.cpp
71 lines (60 loc) · 1.33 KB
/
Day-050.cpp
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include<iostream>
using namespace std;
int getSum(int *arr,int size){
// base case
if(size == 0){
return 0;
}
if(size == 1){
return arr[0];
}
int remainingPart = getSum(arr+1,size-1);
int sum = arr[0] + remainingPart ;
return sum;
}
void print(int arr[],int n){
cout << "size of array is " << n << endl;
for(int i = 0 ; i < n ; i++){
cout << arr[i] << " ";
}
cout << endl;
}
bool linearSearch(int arr[],int size,int k){
print(arr,size);
// 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
if(s>e)
return -1;
int mid = s +(e-s)/2;
//element found
if(arr[mid] == k )
return mid;
if(arr[mid] < k){
return binarySearch(arr,mid+1,e,k);
}
else{
return binarySearch(arr,s,mid-1,k);
}
}
int main (){
int arr[5] = {2,4,7,9,9};
int size = 5;
int sum = getSum(arr, size);
cout << "sum is " << sum << endl;
cout << "linear search " << linearSearch(arr,size,9) << endl ;
int ans = binarySearch(arr,0,4,9);
cout << "binary search " << ans << endl;
return 0;
}