Skip to content

Commit

Permalink
Added binary search
Browse files Browse the repository at this point in the history
  • Loading branch information
chinmayshah99 authored Oct 22, 2017
1 parent e9e6b57 commit 0f26b95
Showing 1 changed file with 68 additions and 0 deletions.
68 changes: 68 additions & 0 deletions Search/BinarySearch/bsearch.cpp
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;
}

0 comments on commit 0f26b95

Please sign in to comment.