Binary search with STL

Hello all, long time since I wrote about C++ thingy. Then let me introduce you to binary search in C++, however in this article I won’t write how to implement Binary search on C++; Instead we use STL’s binary search.

First, create class to provide interface to our data and binary search functionally.

class b_search
{
private:
 int size;
 int *list;
public:
 b_search(int *list, int size)
 {
 this->list = list;
 this->size = size;
 }
 void find(int item)
 {
 if(binary_search(list,list+size,item))
 cout<<item<<" found"<<endl;
 else
 cout<<item<<" not found"<<endl;
 }
};

Then lets use it :

int main()
{
 int me[10] = {1,2,3,4,5,6,7,8,9};
 b_search meFind(me,sizeof(me)/sizeof(me[0]));
 meFind.find(1);
 meFind.find(10);
 return 0;
}

However that class only usable if your data set is int, so lets modify it to be something more generic.

class b_search
{
private:
 int size;
 T *list;
public:
 b_search(T *list, int size)
 {
 this->list = list;
 this->size = size;
 }
 void find(T item)
 {
 if(binary_search(list,list+size,item))
 cout<<item<<" found"<<endl;
 else
 cout<<item<<" not found"<<endl;
 }
};

With template class above you can use it for any basic data type.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s