Friday, April 18, 2014

An example of binary search in C++




Binary search:
1) the array should be arranged in ascending or descending order.
Here using  ascending order
2) In each step,  compares the search key value  to the middle element of the array

Example
double a[]={1.1,1.2, 1.4, 1.6,1.8, 2.0,2.2};
Search 2.0
Create BinarySearch class

code:
#include <iostream> 
using namespace std; 
class BinarySearch //for  ascending order
{
private:
double *Plist;
public:
         BinarySearch(double *list, int listlength);
         void BSearch(int begin, int end, double target);
         ~BinarySearch();  
};
BinarySearch::BinarySearch(double *list, int listlength)
{
Plist= new double[listlength];
for(int i=0; i<listlength;i++)
Plist[i]=list[i];
}
BinarySearch::~BinarySearch()
{
delete []Plist;
}
void BinarySearch::BSearch(int begin, int end, double target)
{
int m;
m=(begin+end)/2;
if(Plist[m]==target)
{
cout<<" The Element   "<<target<<" is found at postion  "<<m+1<<endl;
}
else if(begin>=end){
   cout<<" The Element   "<<target<<" is not found.  "<<endl;
exit(-1);
}
else if(target>Plist[m])
    BSearch(m+1, end, target);
else
    BSearch(begin, m-1, target); 
}

int main()
{
double a[]={1.1,1.2, 1.4, 1.6,1.8, 2.0,2.2};
double target=2.0;
BinarySearch bs(a,7);
bs.BSearch(0, 6, target);
}


Running result:
The Element   2 is found at postion  6
Video: An example of binary search in C++ 

No comments:

Post a Comment