This template class is a linear search algorithm with a simple search function. I have tested it with int
and char
and it seems to be working fine. I would like pointers on how I can make it more efficient and on my coding technique. I do know that the standard library provides this algorithm, i am just doing it for fun and practice
sLinear.h
//Linear search template
#ifndef SLINEAR_H
#define SLINEAR_H
namespace fm
{
template <typename T>
class sLinear
{
T *_list;
T _item;
int _sizeOfList;
public:
sLinear();
sLinear(T *myArray, T item, int size);
~sLinear();
int findItem();
};
//------public methods------
template <typename T>
sLinear<T>::sLinear()
{
_list = nullptr;
_sizeOfList = 0;
}
template <typename T>
sLinear<T>::sLinear(T *myArray, T item, int size)
{
_list = myArray;
_item = item;
_sizeOfList = size;
}
template <typename T>
sLinear<T>::~sLinear()
{
_list = nullptr;
_sizeOfList = 0;
}
template <typename T>
int sLinear<T>::findItem()
{
while (_list != nullptr)
{
for (int i = 0; i < _sizeOfList; i++)
{
if (_list[i] == _item)
{
return i + 1;
}
}
return -1;
}
}
}
#endif
main.h
#include<iostream>
#include "sLinear.h"
using namespace fm;
int main()
{
/* Linear search with integer */
int iList[] = { 1,9,2,6,5,3,7,4,8,0 };
int size = (sizeof(iList) / sizeof((iList[0])));
sLinear<int> mySearch(iList, 8, size);
int k = mySearch.findItem();
if (k == -1)
std::cout << "Item not found!" << std::endl;
else
std::cout << "Item found:" << k << std::endl;
return 0;
}