Skip to content

Instantly share code, notes, and snippets.

@shemul
Created October 20, 2014 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shemul/afcefb8c46c4ea0d029d to your computer and use it in GitHub Desktop.
Save shemul/afcefb8c46c4ea0d029d to your computer and use it in GitHub Desktop.
binary search
#include<iostream>
using namespace std;
int main()
{
int roll[10];
int element ;
cout<<"How much roll you want to input ? : " ;
cin >> element ;
for(int i = 0 ; i < element ; i++)
{
cin >> roll[i];
}
cout<<"Which roll you want to search ? "<<endl ;
int searchs;
cin >> searchs ;
int first = 0;
int last = element-1 ;
int middle = (first+last) /2 ;
while (first <= last)
{
if(roll[middle]<searchs)
{
first = middle+1 ;
} else if(searchs == roll[middle])
{
cout<<searchs <<" found at location " << middle+1<<endl;
break;
} else {
last = middle-1 ;
}
middle =(first+last)/2 ;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment