Searching Through a Sorted List of Integers

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)

Returns: TRUE if the item was found, FALSE if the item was not found.
Boolean Search(const int list[],
               int item,
               int length,
               int& index)
{
  index = 0;
  while (index < length && item > list[index])
    index++;

  return (index < length && item == list[index]);
}
This function would be used in the same way as before. The difference is that the algorithm is much more efficient at finding whether or not the item exists.
int index;

Boolean found = Search(list, 13, 15, index);

if (found)
  cout << "13 was found at index: " << index;
else
  cout << "13 was not found";

A picture of a sorted list is here.

Previous page

Back to Lesson 2 Index
Back to Outline