Ashley Durban SA
2010-08-31 11:17:10 UTC
Therefore, it usually works the same for both sorted and unsorted lists.
However, if the elements of
the list are sorted, then you can somewhat improve the performance of the sequential search
algorithm.
For example, if the search item is not in the list, you can stop the search as soon as you
find an element in the list that is larger than the search item.
Write the function seqOrdSearch to
implement a version of the sequential search algorithm for sorted lists.
Write a test program as well.
#include
#include
template
Iter seqOrdSearch(Iter beg, Iter end, const T& n)
{
for (; beg != end; ++beg)
{
if (*beg == n) break;
if (*beg > n) return end;
}
return beg;
}
int main()
{
std::list
auto i1 = seqOrdSearch(testlist.begin(), testlist.end(), 8);
std::cout << "The number 8 was " << (i1==testlist.end()?"not ":"") << "found\n";
auto i2 = seqOrdSearch(testlist.begin(), testlist.end(), 11);
std::cout << "The number 11 was " << (i2==testlist.end()?"not ":"") << "found\n";
}