Created
November 22, 2017 05:35
-
-
Save myusufid/34956824796eff2f2c2e0b8870674f7e to your computer and use it in GitHub Desktop.
Binary Search with C++ , Thanks thecrazyprogrammer
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 main() | |
{ | |
int search(int [],int,int); | |
int n,i,a[100],e,res; | |
cout<<"How Many Elements:"; | |
cin>>n; | |
cout<<"\nEnter Elements of Array in Ascending order\n"; | |
for(i=0;i<n;++i) | |
{ | |
cin>>a[i]; | |
} | |
cout<<"\nEnter element to search:"; | |
cin>>e; | |
res=search(a,n,e); | |
if(res!=-1) | |
cout<<"\nElement found at position "<<res+1; | |
else | |
cout<<"\nElement is not found....!!!"; | |
return 0; | |
} | |
int search(int a[],int n,int e) | |
{ | |
int f,l,m; | |
f=0; | |
l=n-1; | |
while(f<=l) | |
{ | |
m=(f+l)/2; | |
if(e==a[m]) | |
return(m); | |
else | |
if(e>a[m]) | |
f=m+1; | |
else | |
l=m-1; | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment