[Thomas_H._Cormen]_Algorithms_unlocked(BookZZ.org)
Erfolgreiche ePaper selbst erstellen
Machen Sie aus Ihren PDF Publikationen ein blätterbares Flipbook mit unserer einzigartigen Google optimierten e-Paper Software.
3 Algorithms for Sorting and
Searching
In Chapter 2, we saw three variations on linear search of an array. Can
we do any better? The answer: it depends. If we know nothing about the
order of the elements in the array, then no, we cannot do better. In the
worst case, we have to look through all n elements because if we don’t
find the value we’re looking for in the first n 1 elements, it might be
in that last, nth, element. Therefore, we cannot achieve a better worstcase
running time than ‚.n/ if we know nothing about the order of the
elements in the array.
Suppose, however, that the array is sorted into nondecreasing order:
each element is less than or equal to its successor in the array, according
to some definition of “less than.” In this chapter, we shall see that if
an array is sorted, then we can use a simple technique known as binary
search to search an n-element array in only O.lg n/ time. As we saw in
Chapter 1, the value of lg n grows very slowly compared with n,andso
binary search beats linear search in the worst case. 1
What does it mean for one element to be less than another? When the
elements are numbers, it’s obvious. When the elements are strings of
text characters, we can think of a lexicographic ordering: one element
is less than another if it would come before the other element in a dictionary.
When elements are some other form of data, then we have to
define what “less than” means. As long as we have some clear notion
of “less than,” we can determine whether an array is sorted.
Recalling the example of books on a bookshelf from Chapter 2, we
could sort the books alphabetically by author, alphabetically by title, or,
if in a library, by call number. In this chapter, we’ll say that the books
are sorted on the shelf if they appear in alphabetical order by author,
reading from left to right. The bookshelf might contain more than one
book by the same author, however; perhaps you have several works by
William Shakespeare. If we want to search for not just any book by
1 If you are a non-computer person who skipped the section “Computer algorithms for
computer people” in Chapter 1, you ought to read the material about logarithms on
page 7.