forked from Sjsingh101/Basic-C-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_search.cpp
68 lines (55 loc) · 1.27 KB
/
binary_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
63
64
65
66
67
68
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
std::vector<int> myarray;
// implements binary search
bool binary_search(int number)
{
int higher = myarray.size();
int lower = 0;
int mid;
do
{
mid = (higher + lower) / 2;
if (number == myarray[mid])
{
std::cout << "found at pos: " << mid + 1 << std::endl;
std::cout << myarray[mid] << std::endl;
return true;
}
else if (number > myarray[mid])
lower = mid;
else if (number < myarray[mid])
higher = mid;
if (higher - lower == 1)
return false;
} while (true);
}
bool is_digits(const std::string &str)
{
return std::all_of(str.begin(), str.end(), ::isdigit); // C++11
}
int main(int argc, char const *argv[])
{
/* code */
std::string z;
while(true)
{
std::cin>>z;
if (is_digits(z))
{
int input = stoi(z);
myarray.push_back(input);
}
else
break;
}
std::cout<<"enter number you want to search"<<std::endl;
int k;
std::cin>>k;
bool found = binary_search(k);
if(found == false)
std::cout<<"couldn't find number"<<std::endl;
return 0;
}