forked from mr-70da/AlgortihmsAssignmentOne
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearch.cpp
More file actions
69 lines (62 loc) · 1.55 KB
/
Search.cpp
File metadata and controls
69 lines (62 loc) · 1.55 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include<bits/stdc++.h>
using namespace std;
int IterativeSearch(int arr[], int n, int target) {
for (int i = 0; i < n; ++i) {
if (arr[i] == target) {
return i;
}
}
cout << "Not found target number ";
return -1;
}
int RecursiveSearch(int i, int arr[], int n, int target) {
if (i == n) {
cout << "Not found target number ";
return -1;
}
if (arr[i] == target) {
return i;
}
return RecursiveSearch(i + 1, arr, n, target);
}
int IterativeBinarySearch(int arr[], int n, int target) {
int l = 0, r = n - 1, index = -1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (arr[mid] > target) {
r = mid - 1;
} else {
index = mid;
l = mid + 1;
}
}
if (index == -1 || arr[index] != target) {
cout << "Not found target number ";
return -1;
}
return index;
}
int RecursiveBinarySearch(int low, int high, int arr[], int target) {
if (low > high) {
cout << "Not found target number ";
return -1;
}
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] > target) {
return RecursiveBinarySearch(low, mid - 1, arr, target);
} else {
return RecursiveBinarySearch(mid + 1, high, arr, target);
}
}
//int main() {
// int arr[]={1,2,3,4,5,6,7,8,9};
// int index = IterativeSearch(arr,9,8);
// cout<<index<<endl;
// index = RecursiveSearch(0,arr,9,10);
// cout<<index<<endl;
//
//
//
//}