@@ -7,12 +7,71 @@ The number 3 is [not] present in the array.
77*/
88
99#include < iostream>
10+ #include < algorithm>
11+ #include < vector>
1012using namespace std ;
1113
12- int main ()
13- {
14- // placeholder
15- int N[10 ] = {3 , 4 , 5 , 1 , 2 , 3 , 4 , 9 , 13 , 0 };
14+ const int ZERO = 48 ;
15+ const int NINE = 57 ;
16+ const int MAX_DIGIT = 10 ;
17+ const int MINUS = 45 ;
18+
19+ const std::string ERROR_COLOR = " \033 [31m" ;
20+ const std::string NORMAL_COLOR = " \033 [0m" ;
21+
22+ double insertNumber (const std::string& msg);
23+ bool checkStringIsNumber (std::string in);
24+ template <typename T>
25+ int binarySearch (T item, vector<int >&collection);
26+
27+ int main (){
28+ vector<int > collection = {3 , 4 , 5 , 1 , 2 , 3 , 4 , 9 , 13 , 0 };
29+ sort (collection.begin (), collection.end ());
30+
31+ auto n = insertNumber (" Insert number: " );
32+
33+ int pos;
34+ if (pos = binarySearch (n, collection) == -1 ) cout << " Value Not Found" ;
35+ else cout << " Value found at " << pos << " position" ;
1636
1737 return 0 ;
1838}
39+
40+ template <typename T>
41+ int binarySearch (T item, vector<int >&collection) {
42+ int start = 0 ;
43+ int end = collection.size ()-1 ;
44+ int center;
45+ do {
46+ center = (start + end) / 2 ;
47+ if (collection[center] == item) return center;
48+ if (item > collection[center]) start = center+1 ;
49+ else end = center-1 ;
50+ } while (start <= end);
51+ return -1 ;
52+ }
53+
54+
55+ double insertNumber (const std::string& msg){
56+ std::string insert;
57+ bool isCorrect = true ;
58+ do {
59+ if (!isCorrect) std::cout << ERROR_COLOR << " [Insert a valid input] " << NORMAL_COLOR;
60+ std::cout << msg;
61+ getline (std::cin, insert);
62+ } while (!(isCorrect = checkStringIsNumber (insert)));
63+
64+ return std::stod (insert);
65+ }
66+
67+ bool checkStringIsNumber (std::string in){
68+ if (in.empty ()) return false ;
69+ if (in.size () > MAX_DIGIT) return false ;
70+ for (std::size_t i = 0 ; i < in.size (); ++i){
71+ if ((in[i] < ZERO || in[i] > NINE)){
72+ if (i == 0 && in[i] == MINUS) continue ;
73+ return false ;
74+ }
75+ }
76+ return true ;
77+ }
0 commit comments