forked from bgopesh/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.cpp
62 lines (46 loc) · 1.05 KB
/
search.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
#include <iostream>
#include <vector>
using namespace std;
bool binarySearch(std::vector<int> sorted_list, int item)
{
if(sorted_list.empty())
{
return false;
}
auto litr = sorted_list.begin();
auto ritr = sorted_list.end()-1;
while(litr <= ritr)
{
int leftindex = std::distance(sorted_list.begin(), litr);
int rightindex = std::distance(sorted_list.begin(), ritr);
int mid = (leftindex + ((rightindex-leftindex)/2));
if(sorted_list.at(mid) == item)
{
return true;
}
if(item < sorted_list.at(mid))
{
ritr = sorted_list.begin() + mid-1;
}
else
{
litr = sorted_list.begin()+ mid+1;
}
}
return false;
}
int main()
{
std::vector<int> sorted_list{};
int item = -10;
bool result = binarySearch(sorted_list, item);
if(result)
{
cout << "item " <<item << "is found" <<endl;
}
else
{
cout << "not found" << endl;
}
return 0;
}