Created
April 4, 2018 08:22
-
-
Save kamaubrian/84ee1220ca66cf97291b577f3c2fa38b to your computer and use it in GitHub Desktop.
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
#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