Skip to content

Instantly share code, notes, and snippets.

@myusufid
Created November 22, 2017 05:35
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 myusufid/34956824796eff2f2c2e0b8870674f7e to your computer and use it in GitHub Desktop.
Save myusufid/34956824796eff2f2c2e0b8870674f7e to your computer and use it in GitHub Desktop.
Binary Search with C++ , Thanks thecrazyprogrammer
#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