Sun Dec 08 2019

Linear Search

C++ Programming1461 views

File Name: linear-search.cpp

#include<iostream>
using namespace std;

/* Preprocessor */
#define get_size(array) (sizeof((array))/sizeof((array[0])))

template <class t>
class linear {
	t *list;
	int length;
	public:
	linear(t *data, int size) {
		list = data;
		length = size;
	}
	
	bool search(t item) {
		bool found = false;
		for(int i = 0; i < length; i++) {
			if(list[i] == item) {
				cout << "Item found at Location: " << i+1 << endl;
				found = true;
				break;
			}
		}

		return found;
	}
};


int main() {

	/* Linear search with integer */
	int iList[] = {1,9,2,6,5,3,7,4,8,0};
	linear <int> intSearch(iList, get_size(iList));
	if(!intSearch.search(8))
		cout << "Item not found!" << endl;

	/* Linear search with float */
	float fList[] = {1.5,9.2,2.3,6.4,5.2,3.8,7.9,8.1,0.2};
	linear <float> floatSearch(fList, get_size(fList));
	if(!floatSearch.search(8))
		cout << "Item not found!" << endl;

	/* Linear search with string */
	string sList[] = {"be","to","go","fun","find","search","c++","java"};
	linear <string> strSearch(sList, get_size(sList));
	if(!strSearch.search("c++"))
		cout << "Item not found!" << endl;

	return 0;
}


/* Output */
Item found at Location: 9
Item not found!
Item found at Location: 7
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.