C++ Program for Binary Search
Master C++ with Real-time Projects and Kickstart Your Career Start Now!!
Program 1
// Program for Binary Search
#include<iostream>
#define clrscr() system("cls")
using namespace std;
int main()
{
int ar[500],n,i,j,temp,low,high,mid,f,s;
clrscr();
xyz:cout<<"\nEnter the limit";
cin>>n;
if(n>500)
{
cout<<"\nInvalid limit(0-500 only) enter again";
goto xyz;
}
else
{
cout<<"\nEnter elements in array\n";
for(i=0;i<n;i++)
cin>>ar[i];
// Sort the array
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(ar[j]<ar[i])
{
temp=ar[i];
ar[i]=ar[j];
ar[j]=temp;
}
}
}
// Binary Search
low=0;
high=n-1;
cout<<"\nEnter element for search";
cin>>s;
f=0;
while(low<=high)
{
mid=(low+high)/2;
if(s==ar[mid])
{
f=1;
break;
}
else if(s>ar[mid])
low=mid+1;
else
high=mid-1;
}
if(f==1)
cout<<"'\n*******Searching Success*******";
else
cout<<"'\n*******Element not fouund*******";
// for(i=0;i<n;i++)
// cout<<ar[i]<<"\n";
}
}
Did we exceed your expectations?
If Yes, share your valuable feedback on Google

