C++ Program to Search a no. Using (Binary Search Method)
5:27 AM
use header files iostream.h,process.h and conio.h then
void main()
{
int
ar[100],beg,mid,end,i,n,search;
clrscr();
cout<<"How
many numbers in the array: ";
cin>>n;
cout<<"Enter
"< ";
for(i=0;i
cin>>ar[i];
beg=0;
end=n-1;
cout<<"Enter
a number to search: ";
cin>>search;
while(beg<=end)
{
mid=(beg+end)/2;
if(ar[mid]==search)
{
cout<<"\nItem
found at position "<<(mid+1);
getch();
exit(0);
}
if(search>ar[mid])
beg=mid+1;
else
end=mid-1;
}
cout<<"\nSorry!
"<
getch();
}
Output:-
How many numbers in the array: 3
Enter 3 numbers in ascending order -->
1
5
7
Enter a number to search: 4
Sorry! 4 doesnot found.
0 comments