-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch-functions.cpp
More file actions
69 lines (65 loc) · 1.22 KB
/
Copy pathsearch-functions.cpp
File metadata and controls
69 lines (65 loc) · 1.22 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
// Searching algorithms
// Linear, Binary, Interpolation
#include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
// Linear Search
bool linear(vi A, int key) // O(n)
{
for (auto element : A)
{
if (element == key)
return true;
}
return false;
}
// Binary Search
bool binary(vi A, int key) // O(log n)
{
sort(A.begin(), A.end());
int mid, start = 0, end = A.size() - 1;
while (start <= end)
{
mid = start + (end - start) / 2;
if (A[mid] == key)
return true;
else if (A[mid] > key)
end = mid - 1;
else
start = mid + 1;
}
return false;
}
// Interpolation Search
bool interpolation(vi A, int key) // O(log n), best: O(log log n)
{
sort(A.begin(), A.end());
int idx, start = 0, end = A.size() - 1;
while (start <= end)
{
idx = start + (((end - start) / (A[end] - A[start])) * (key - A[start]));
if (A[idx] == key)
return true;
else if (A[idx] > key)
end = idx - 1;
else
start = idx + 1;
}
return false;
}
int main()
{
int n, key;
cout << "# elements: ";
cin >> n;
vi A(n);
cout << "enter array: ";
for (int i = 0; i < n; i++)
cin >> A[i];
cout << "key: ";
cin >> key;
if (algo_name(A, key)) //algo_name replace by function name
cout << "found";
else
cout << "not found";
}