Mon Dec 09 2019

STL Binary Search

C++ Programming2857 views

File Name: stl-binary-search.cpp

#include<iostream>
#include<algorithm>
using namespace std;

template <class t>
class b_search {
	int size;
	t *list;
	public:
		b_search(t *data, int length) {
			list = data;
			size = length;
		}

		void find(t item) {

			/* Search data using STL 'binary_search()' */
			if (binary_search(list, list+size, item))
				cout << item << " found!" << endl;
			else
				cout << item << " not found!" << endl;
		}
};

int main() {

	/* Binary search using integer */
	int iArray[] = {10,20,30,40,50,60,70,80,90};
	int iSize = (sizeof((iArray))/sizeof((iArray[0])));
	b_search<int> intSearch(iArray, iSize);	
	intSearch.find(30);

	/* Binary search using float */
	float fArray[] = {1.22,2.31,3.50,4.55,5.23,6.70,7.11,8.32,9.12};
	int fSize = (sizeof((fArray))/sizeof((fArray[0])));
	b_search<float> floatSearch(fArray, fSize);	
	floatSearch.find(3);

	/* Binary search using string */
	string sArray[] = {"be","c++","fun","find","go","java","search","to"};
	int sSize = (sizeof((fArray))/sizeof((fArray[0])));
	b_search<string> stringSearch(sArray, sSize);	
	stringSearch.find("fun");

	return 0;
}



/* Output */
30 found!
3 not found!
fun found!
Reference:

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.