9.1 Minimum and Maximum: Length (A) N. A) Min A (1) I 2 To Length (A) Min A (I) Min A (I) Min
9.1 Minimum and Maximum: Length (A) N. A) Min A (1) I 2 To Length (A) Min A (I) Min A (I) Min
M INIMUM ( A)
1 min ← A[1]
2 for i ← 2 to length[A]
3 do if min > A[i]
4 then min ← A[i]
5 return min
we process elements in pairs. We compare pairs of elements from the input first
with each other, and then we compare the smaller to the current minimum and the
larger to the current maximum, at a cost of 3 comparisons for every 2 elements.
Setting up initial values for the current minimum and maximum depends on
whether n is odd or even. If n is odd, we set both the minimum and maximum
to the value of the first element, and then we process the rest of the elements in
pairs. If n is even, we perform 1 comparison on the first 2 elements to determine
the initial values of the minimum and maximum, and then process the rest of the
elements in pairs as in the case for odd n.
Let us analyze the total number of comparisons. If n is odd, then we perform
3 ⌊n/2⌋ comparisons. If n is even, we perform 1 initial comparison followed by
3(n − 2)/2 comparisons, for a total of 3n/2 − 2. Thus, in either case, the total
number of comparisons is at most 3 ⌊n/2⌋.
Exercises
9.1-1
Show that the second smallest of n elements can be found with n + ⌈lg n⌉ − 2
comparisons in the worst case. (Hint: Also find the smallest element.)
9.1-2 ⋆
Show that ⌈3n/2⌉ − 2 comparisons are necessary in the worst case to find both the
maximum and minimum of n numbers. (Hint: Consider how many numbers are
potentially either the maximum or minimum, and investigate how a comparison
affects these counts.)
The general selection problem appears more difficult than the simple problem of
finding a minimum. Yet, surprisingly, the asymptotic running time for both prob-
lems is the same: 2(n). In this section, we present a divide-and-conquer algorithm
for the selection problem. The algorithm R ANDOMIZED -S ELECT is modeled af-
ter the quicksort algorithm of Chapter 7. As in quicksort, the idea is to partition
the input array recursively. But unlike quicksort, which recursively processes both
sides of the partition, R ANDOMIZED -S ELECT only works on one side of the parti-
tion. This difference shows up in the analysis: whereas quicksort has an expected
running time of 2(n lg n), the expected time of R ANDOMIZED -S ELECT is 2(n).
R ANDOMIZED -S ELECT uses the procedure R ANDOMIZED -PARTITION intro-
duced in Section 7.3. Thus, like R ANDOMIZED -Q UICKSORT, it is a randomized al-
gorithm, since its behavior is determined in part by the output of a random-number