Tuesday, 29 May 2012

Hi friends,
Here we will going to discuss the working of the bunary search algorithm for searching of elements in sorted number array.

Binary search algorithm are fast as they search dividing the array in two part from middle as i have used here in my exp. md variable for middle part so it's complexity rate is low compared two other algorithm but the restriction is that it require sorted list.

Here is the Source file for what we going to discuss:

download binarys.cpp



Here i have assumed that user enters the number in ascending order.


class binary
{
int arr[20];
int n,x;
int lb,ub,md;
public:
binary();
void getdata();
void search();
};

as you can see above i have first created class binary in which declared one array, middle variable md, start position lb, ending position ub.

Now Here is definition for getdata() function;


void binary :: getdata()
{
cout<<"Enter how many element you want to enter:"<<endl;
cin>>n;
for(int i=0;i<n;i++)
{       cout<<"Enter Element forp["<<i<<"]"<<endl;
cin>>arr[i];
}
cout<<"Eneter the element to be searched";
cin>>x;
}


Suppose we have chose array of nine for simplycity then array should store like this :
1 2 3 4 5 6 7 8 9

Now look code for search() function :


void binary :: search()
{


lb =1;
ub = n;
while(lb<=ub)
{
md = (lb+ub)/2;
if(x<arr[md])
{
ub = md -1;


}
else if(x>arr[md])
{
lb = md +1;


}
else
{
cout<<"Search successful\n";
cout<<"X is at posistion"<<md+1<<endl;
getch();
exit(1);
}
}
}


Now as you can see statement md = (lb+ub)/2; divides the array logically from middle like  given in below table. 


1 2 3 4 Middle=5 6 7 8 9

Here as we can array of nine elements divided into five parts from middle now element that we desire to search is searched in either of direction depending on element value ,after successful search program gives element position in array.

After running  the program program gives output like this:

Here if you want to serch an unsorted array of numbers then you have to first to sort it, try your self if you want tutorial for sort array or any other help visit my site at here:

visit my site

Here is source file of above program to download:

download binarys.cpp

So that's it!