Skip to content

Instantly share code, notes, and snippets.

@kamaubrian
Created April 4, 2018 08:22
Show Gist options
  • Save kamaubrian/84ee1220ca66cf97291b577f3c2fa38b to your computer and use it in GitHub Desktop.
Save kamaubrian/84ee1220ca66cf97291b577f3c2fa38b to your computer and use it in GitHub Desktop.
#include <iostream>
using namespace std;
int a[6]={20,5,1,3,17,3};
bool binarySearch(int first, int last, int key);
int main(){
int key;
cout<<"Enter the item to search"<<endl;
cin>>key;
bool found=false;
found=binarySearch(0,5,key);
if(found){
cout<<key<<"is found"<<endl;
}else{
cout<<key<<"not found"<<endl;
}
}
bool binarySearch(int first, int last, int key){
int index = -1;
if (first > last)
return false;
else {
index = (first + last)/2;
if (key == a[index])
return true;
else if (key < a[index])
return binarySearch(first, index -1, key);
else
return binarySearch(index + 1, last, key);
} //end else
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment