u

Thursday 5 January 2012

C++ Program to depict the usage of Binary Search Technique


Program to depict the usage of Binary Search Technique. (It is assumed that the list of numbers in an array is  stored in ascending order).

 #include<iostream.h>
#include<conio.h>
main()
{
int num[10],m,min,max,mid,pp;
clrscr();
cout<<"Enter any ten numbers as elements ofan array in";
 cout<<" ascending order "<<endl;
for (int i=0;i<10;i++)
{
cin>>num[i];
}
cout<<endl<<"Enter number to search ";
cin>>m;
cout<<endl;
min = 0;
max = 9;
pp = -1;
while ((min<= max)&&(pp == -1))
{
mid = (min+max)/2;
if (num[mid] == m)
pp = mid;
else
if (num[mid]<m)
min = mid + 1;
else
max = mid - 1;
}
if (pp>-1)
cout<<"The element "<<m<<" lies in the array"<<" at "<<pp+1<<" position";
else
cout<<"The element does not lie in the array";
cout<<endl;
cout<<"Program over....press any key to continue";
getch();
return 0;
}

0 comments:

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More