Thursday, October 21, 2010

13.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;
}

No comments:

Post a Comment