From 0f26b95ab109a3923e7bc9ed4b36a5ddc0f94282 Mon Sep 17 00:00:00 2001 From: Chinmay Shah Date: Sun, 22 Oct 2017 18:05:50 +0530 Subject: [PATCH] Added binary search --- Search/BinarySearch/bsearch.cpp | 68 +++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Search/BinarySearch/bsearch.cpp diff --git a/Search/BinarySearch/bsearch.cpp b/Search/BinarySearch/bsearch.cpp new file mode 100644 index 00000000..aa0e0c29 --- /dev/null +++ b/Search/BinarySearch/bsearch.cpp @@ -0,0 +1,68 @@ +#include +#include +#include +#include + +std::vector 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"<>k; + bool found = binary_search(k); + if(found == false) + std::cout<<"couldn't find number"<