-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathe7.cpp
65 lines (59 loc) · 1.47 KB
/
e7.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
//
// Created by martin on 10/18/22.
//
#include "../std_lib.h"
template < typename T >
auto binary_search (vector<T> v, T to_find)
{
int low = 0;
auto high = int(v.size() - 1);
// This below check covers all cases , so need to check
// for mid=low-(high-low)/2
while (high - low > 1)
{
int middle = ( high + low ) / 2;
if (v[middle] < to_find)
{
low = middle + 1;
}
else
{
high = middle;
}
}
if (v[low] == to_find)
{
cout << "Found \"" << to_find << "\" at index " << low << endl;
return low;
}
else if (v[high] == to_find)
{
cout << "Found \"" << to_find << "\" at index " << high << endl;
return high;
}
else
{
cout << "\"" << to_find << "\" not found" << endl;
return -1;
}
}
int main (int argc, char *argv[])
{
header("int test", true);
vector<int> vi = { 9, 1, 3, 5, 4, 5, 6 };
sort(vi);
print(vi);
binary_search(vi, 5);
header("string test");
vector<string> vs = { "James Bond",
"King Kong",
"Jeanne d'Arc",
"Dr. Who",
"Bruce Lee",
"Jason Bourne",
"Vlad the Impaler" };
sort(vs);
print(vs);
binary_search(vs, string("Dr. Who"));
return EXIT_SUCCESS;
}