This preview shows pages 1–2. Sign up to view the full content.
04/15/09
20:34:08
1
34
CS61B:
Lecture 34
Friday, April 17, 2009
Today’s reading:
SELECTION
=========
Suppose that we want to find the kth smallest key in a list.
In other words,
we want to know which item has index j if the list is sorted (where j = k  1).
We could simply sort the list, then look up the item at index j.
But if we
don’t actually need to sort the list, is there a faster way?
This problem is
called _selection_.
One example is finding the median of a set of keys.
If n keys are numbered
from 0 to n  1 (where n is odd), we are looking for the item whose index is
j = (n  1) / 2 in the sorted list.
Quickselect

We can modify quicksort to perform selection for us.
Observe that when we
choose a pivot v and use it to partition the list into three lists I1, Iv, and
I2, we know which of the three lists contains index j, because we know the
lengths of I1 and I2.
Therefore, we only need to search one of the three
lists.
Here’s the quickselect algorithm for finding the item at index j  that is,
having the (j + 1)th smallest key.
Start with an unsorted list I of n input items.
Choose a pivot item v from I.
Partition I into three unsorted lists I1, Iv, and I2.
 I1 contains all items whose keys are smaller than v’s key.
 I2 contains all items whose keys are larger than v’s.
 Iv contains the pivot v.
 Items with the same key as v can go into any of the three lists.
(In listbased quickselect, they go into Iv; in arraybased quickselect,
they go into I1 and I2, just like in arraybased quicksort.)
if (j < I1) {
Recursively find the item with index j in I1; return it.
} else if (j < I1 + Iv) {
Return the pivot v.
} else {
// j >= I1 + Iv.
Recursively find the item with index j  I1  Iv in I2; return it.
}
The advantage of quickselect over quicksort is that we only have to make one
recursive call, instead of two.
Since we make at most _one_ recursive call at
_every_ level of the recursion tree, quickselect is much faster than quicksort.
I won’t analyze quickselect here, but it runs in Theta(n) average time if we
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 '01
 Canny
 Data Structures, Sort

Click to edit the document details