-
Notifications
You must be signed in to change notification settings - Fork 0
/
lec033.cpp
100 lines (78 loc) · 2.55 KB
/
lec033.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
//? Recursion Practise
#include<iostream>
using namespace std;
bool isSorted(int arr[], int start, int size) { //comparing each element with all preceding elements, then calling itself to compare next element with its preceding
if (start == size-1 || size == 0 || size == 1) { //base case
return 1;
}
for(int i=start+1; i<size; i++) { //comparing each element with the start element (checking whether smaller or not) [UNNECESSARY]
if (arr[start] > arr[i]) {
return 0;
}
}
bool sorted = isSorted(arr, start+1, size); //if every element is smaller than start, recall the function with next element to compary with others
return sorted;
}
bool isSortedFaster(int arr[], int size) { //compare only adjacent elements and call itself for comparing next adjacent elements
if (size == 0 || size == 1) {
return 1;
}
if (arr[0] > arr[1]) {
return 0;
}
bool remaining = isSortedFaster(arr+1, size-1); //pass the array without its first element as it has already been compared
return remaining;
}
int arraySum(int arr[], int size, int sum) {
if (size == 0)
return sum;
int remaining = arraySum(arr+1, size-1, sum+arr[0]);
return remaining;
}
int arraySumAnother(int arr[], int size) {
if (size == 0)
return 0;
if (size == 1)
return arr[0];
int remaining = arraySumAnother(arr+1, size-1);
return arr[0] + remaining;
}
bool linearSearch(int arr[], int size, int item) {
if (size == 0)
return 0;
if (arr[0] == item) {
return 1;
}
bool temp = linearSearch(arr+1, size-1, item);
return temp;
}
int linearSearchIndex(int arr[], int index, int size, int item) { //to be completed later
if (size == 0)
return 0;
if (arr[index] != item) {
int temp = linearSearch(arr, index+1, size-1, item);
return temp;
} else {
return index;
}
}
bool binarySearch(int *arr, int s, int e, int item) {
if (s>e) {
return 0;
}
int mid = s + (e-s)/2;
if (arr[mid] == item) {
return 1;
} else if (arr[mid] < item) {
return binarySearch(arr, mid+1, e, item);
} else {
return binarySearch(arr, s, mid-1, item);
}
}
int main() {
int arr[7] = {2, 3, 4, 5, 7, 7, 8};
cout<< isSorted(arr, 0, 7) <<endl;
cout<< isSortedFaster(arr, 7) <<endl;
cout<< arraySum(arr, 7, 0) <<endl;
cout<< linearSearch(arr, 7, 6) <<endl;
}