# 34 - 11/17/10 20:54:47 CS61B: Lecture 34 Monday, November...

This preview shows pages 1–2. Sign up to view the full content.

11/17/10 20:54:47 1 34 CS61B: Lecture 34 Monday, November 15, 2010 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 list-based quickselect, they go into Iv; in array-based quickselect, they go into I1 and I2, just like in array-based 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 select pivots randomly. We can easily modify the code for quicksort on arrays, presented in Lecture 32,

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.

## This note was uploaded on 01/10/2012 for the course CS 61B taught by Professor Canny during the Fall '01 term at Berkeley.

### Page1 / 2

34 - 11/17/10 20:54:47 CS61B: Lecture 34 Monday, November...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online