CSU200 Discrete Structures
Fall 2005
September 7, 2005
Algorithms for Search
Searching and sorting are two of the most fundamental and widely encountered problems in
computer science. In this handout, we describe four algorithms for search.
Given a collection of objects, the goal of
search
is to ﬁnd a particular object in this collection
or to recognize that the object does not exist in the collection. Often the objects have
key values
on which one searches and
data values
which correspond to the information one wishes to retrieve
once an object is found. For example, a telephone book is a collection of
names
(on which one
searches) and
telephone numbers
(which correspond to the data being sought). For the purposes of
this handout, we shall consider only searching for key values (
e.g.
, names) with the understanding
that in reality, one often wants the data associated with these key values.
The collection of objects is often stored in a list or an array. Given a collection of
n
objects
in an array
A
[1
. . n
], the
i
th element
A
[
i
] corresponds to the key value of the
i
th object in the
collection. Often, the objects are sorted by key value (
e.g.
, a phone book), but this need not be
the case. Diﬀerent algorithms for search are required if the data is sorted or not.
The input to a search algorithm is an array of objects
A
, the number of objects
n
, and the key
value being sought
x
. In what follows, we describe four algorithms for search.
1
Unordered Linear Search
Suppose that the given array was not necessarily sorted. This might correspond, for example, to a
collection exams which have not yet been sorted alphabetically. If a student wanted to obtain her
exam score, how could she do so? She would have to search through the entire collection of exams,
onebyone, until her exam was found. This corresponds to the
unordered linear search
algorithm.
UnorderedLinearSearch
[
A, n, x
]
1
for
i
←
1
to
n
2
do if
A
[
i
] =
x
3
then return
i
4
else
i
←
i
+ 1
5
return
“
x
not found”
Note that in order to determine that an object does not exist in the collection, one needs to search
through the
entire
collection.
Now consider the following array:
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
This is the end of the preview.
Sign up
to
access the rest of the document.
 Spring '10
 JenniferChen
 Array, Madrid Metro, Metropolitana di Napoli, phone book

Click to edit the document details