Searching Through a Generic Unsorted List

You need to make a new type using the typedef keyword:
typedef type ItemType
list - the list to be searched
item - the item we're looking for
length - the number of elements in the list
index - the location of the item (if found)
found - flag indicating if item was found
void Search(const ItemType list[],
            ItemType item,
            int length,
            int& index,
            Boolean& found)
{
  index = 0;
  while (index < length && item != list[index])
    index++;

  found = (index < length);
}
If ItemType is a floating point type, we would need to modify the test in the while loop:
while (index < length && fabs(item - list[index] >= EPSILON))
  index++;
EPSILON is assumed to be defined elsewhere as a global constant.

Previous page
Next page

Back to Lesson 2 Index
Back to Outline