//BINARY SEARCH
#include<iostream.h>
#include<conio.h>
void main()
{
int a[20],n,i,top,bottom,mid,f,s;
clrscr();
cout<<"Enter the value of n elements:--";
cin>>n;
cout<<"Enter the elements:--"<<endl;
for(i=0;i<n;i++)
{
cin>>a[i];
}
cout<<"Enter the element to be searched:--";
cin>>s;
top=0;
bottom=n-1;
f=0;
while(top<=bottom && f==0)
{
mid=(top+bottom)/2;
if(s>a[mid])
{
top=mid+1;
}
else if(s<a[mid])
{
bottom=mid-1;
}
else
{
f=1;
}
}
if(f==1)
{
cout<<"Element found";
}
else
{
cout<<"Element not found.";
}
getch();
}
No comments:
Post a Comment