This method assumes that the set of elements in a list is first arranged in ascending or descending order. The list is initially divided into two parts and the mid point is found. If the number to be searched is less than the value of the element at the mid point, it implies that the given number lies in the first part of the list, otherwise the given number lies in the second part of the list. This is illustrated as follows:
Example
The program illustrates searching a number in a given list using Binary search.
#include <iostream.h>
const int n=5;
void main()
{
int i,s,m,low=0,mid,top,p;
int a[n];
cout<<"Enter the number of elements";
cin>>m;
cout<<"Enter the elements in sorted order";
for(i=0;i<m;i++)
cin>>a[i];
cout<<"Enter the element to be searched ";
cin>>s;
top=m;
while(low<=top)
{
mid=(low+top )/2;
if (s==a[mid])
{
cout<<endl;
cout<<"Element is present in posifion "<<mid+1;
p=1;
break;
}
else
if (s<a[mid])
top=mid-1;
else
low=mid+ 1;
}
if (p!=1)
cout<<"Element is not present in the list";
}
Input and Output:
Enter the number of elements 5
Enter the elements in sorted order 2 4 7 9 10
Enter the element to be searched 7
Element is present in position 3
Dinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.
Related Articles
Basic Courses
Advance Courses