Suppose one is provided with a list of people in the class, and one is asked to look up the name Debbie
Drawe. A sequential search is a “brute force” algorithm that one can use. With a sequential search, the
algorithm simply compares each name in the list to the name for which we are searching. The search ends when
the algorithm finds a matching name, or when the algorithm has inspected all names in the list.
Here is pseudocode for the sequential search. The double forward slash “//” indicates a comment. Note,
too, the way we use the variable index to refer to a particular element in list_of_names. For instance,
list_of_names[3] is the third name in the list.
Sequential_Search(list_of_names, name)
length <-- length of list_of_names
match_found <-- false
index <-- 1
// While we have not found a match AND
// we have not looked at every person in the list,
// (The symbol <= means "less than or equal to.")
// continue ...
// Once we find a match or get to the end of the list,
// we are finished
while match_found = false AND index <= length {
// The index keeps track of which name in the list
// we are comparing with the test name.
// If we find a match, set match_found to true
if list_of_names[index] = name then
match_found <-- true
index <-- index + 1
}
// match_found will be true if we found a match, and
// false if we looked at every name and found no match
return match_found
end
16 ALGORITHMS [CHAP. 2
GCD ( a, b ) Function name and arguments
While b ! = 0 { ! = means “not equal”
indentation shows what to do while b ! = 0
r <-- a modulo b set r = a modulo b ( = remainder a/b)
a <-- b set a = original b
b <-- r set b = r (i.e., the remainder)
} border of the “while” repetition
return a when b = 0, return value of a as the GC
No comments:
Post a Comment