|
|
COT 5410-01 Fall 2004 Algorithms Chris Lacher Notes 4: Searching in Sequential Structures |
for ( s = S.Begin() ; s != S.End() ; s = S.Next(s) )
{}
traverses the entire set S
Locator sequential_search (traversable set S of elements of type T, T t)
{
for ( s = S.Begin() ; s != S.End() ; s = S.Next(s) )
{
if (t == s)
return s;
}
return S.End();
}
size_t r_binary_search (T* A, size_t L, size_t H, T t)
// pre: A[L,H) is sorted - note H is past the end of the search
// post: no change in A
// return: index of first occurrence of t in A, or
// index where t should be inserted to retain sorted order
{
size_t M;
if (L < H) // search range is not empty
{
M = (L + H)/2;
if (A[M] < t) // t is not in [L..M]
return r_binary_search (A, M+1, H, t);
else // t is not in [M..H)
return r_binary_search (A, L, M, t);
}
else
return H;
}
size_t i_binary_search (T* A, size_t L, size_t H, T t)
// pre: A[L,H) is sorted - note H is past the end of the search
// post: no change in A
// return: index of first occurrence of t in A, or
// index where t should be inserted to retain sorted order
{
size_t M;
while (L < H)
{
M = (L + H)/2;
if (A[M] < t) // t is not in [L..M]
L = M + 1;
else // t is not in [M..H)
H = M;
}
return H;
}