forked from tarun620/ACM-ICPC-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
e9e6b57
commit 0f26b95
Showing
1 changed file
with
68 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
#include <iostream> | ||
#include <vector> | ||
#include <string> | ||
#include <algorithm> | ||
|
||
std::vector<int> myarray; | ||
|
||
|
||
// implements linear 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; | ||
} |