PROGRAM OF BINARY SEARCH THROUGH C++.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int arr[5];
int max=5;
int n;
cout<<" Enter the elements of array";
for(int i=0;i<max;i++)
{
cin>>arr[i];
}
cout<<"Enter the elements to search";
cin>>n;
int lb=0,ub=max-1;
int mid=(lb+ub)/2;
while(lb<=ub && arr[mid]!=n)
{
if(n<arr[mid])
ub=mid-1;
else
lb=mid+1;
mid=(lb+ub)/2;
}
if(arr[mid]==n)
cout<<"\nSearch is Successful. "<<n<<" is found at "<<mid+1;
else
cout<<"\nUnSuccessful.";
getch();
}
#include<conio.h>
void main()
{
clrscr();
int arr[5];
int max=5;
int n;
cout<<" Enter the elements of array";
for(int i=0;i<max;i++)
{
cin>>arr[i];
}
cout<<"Enter the elements to search";
cin>>n;
int lb=0,ub=max-1;
int mid=(lb+ub)/2;
while(lb<=ub && arr[mid]!=n)
{
if(n<arr[mid])
ub=mid-1;
else
lb=mid+1;
mid=(lb+ub)/2;
}
if(arr[mid]==n)
cout<<"\nSearch is Successful. "<<n<<" is found at "<<mid+1;
else
cout<<"\nUnSuccessful.";
getch();
}
No comments:
Post a Comment