Skip to content

Instantly share code, notes, and snippets.

@ThakurSahabUPse
Last active October 21, 2017 14:49
Show Gist options
  • Select an option

  • Save ThakurSahabUPse/ce45e1744e65916bd72fa02c4bc3f3c2 to your computer and use it in GitHub Desktop.

Select an option

Save ThakurSahabUPse/ce45e1744e65916bd72fa02c4bc3f3c2 to your computer and use it in GitHub Desktop.
Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or th…
#include<iostream>
using namespace std;
bool isBinarySearchFoundElement(int* arrData,int searchElement,int left, int right){
if(left > right){
return false;
}
int mid = left + (right-left)/2;
if(arrData[mid] == searchElement){
return true;
}else if(searchElement < arrData[mid]){
isBinarySearchFoundElement(arrData,searchElement,left,mid-1);
}else{
isBinarySearchFoundElement(arrData,searchElement,mid+1,right);
}
return false;
}
bool isFoundData(int* arrData,int element){
int right = sizeof(arrData)/sizeof(arrData[0]);
bool isDataFound = isBinarySearchFoundElement(arrData,element,0,right);
return isDataFound;
}
int main(){
int element;
//Array must be sorted
int arrData[] = {10,20,30,144,232,353};
cout<<"Enter element to search:"<<endl;
cin>>element;
bool isFound = isFoundData(arrData,element);
if(isFound == true){
cout<<"Element found in array!"<<endl;
}else{
cout<<"Element does not exist in array!";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment