WAP TO IMPLEMENT BINARY SEARCH - Algorithm Design and Analysis Lab file


WAP TO IMPLEMENT BINARY SEARCH

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n,j,data,lb=0,mid,a[7];
cout<<" enter the size of array \n";
cin>>n;
cout<<"enter the array\n";
for(int i=0;i<n;i++)
{
cin>>a[i];
}
int ub=n-1;
/*
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
*/
cout<<"enter the data:\n";
cin>>data;
mid=(lb+ub)/2;
while((lb<=ub)&&(a[mid]!=data))
{

if(a[mid]<data)
{
lb=mid+1;
}
else if(a[mid]>data)

{
ub=mid-1;
}
mid=(lb+ub)/2;
}
cout<<a[mid];
if(a[mid]==data)
{
cout<<"DATA found at "<<mid;
}
else
{
cout<<"NOT found\n";
}

getch();
}


OUTPUT :


No comments:

Post a Comment