Linear-Time Selection
Understand the efficiency and effectiveness of the linear-time selection algorithm.
We'll cover the following...
During our discussion of quick-sort, we claimed in passing that we can find the median of an unsorted array in linear time. The first such algorithm was discovered by Manuel Blum, Bob Floyd, Vaughan Pratt, Ron Rivest, and Bob Tarjan in the early 1970s. Their algorithm actually solves the more general problem of selecting the -th smallest element in an -element array, given the array and the integer as inputs, by using a variant of an algorithm called quickselect or one-armed quick-sort. Quickselect was first described by Tony Hoare in 1961, literally on the same page where he first published quick-sort.
Quick-select
The generic quickselect algorithm chooses a pivot element, partitions the array using the same partition subroutine as quick-sort, and then recursively searches only one of the two subarrays, specifically the one that contains the -th smallest element of the original input array. The pseudocode for quickselect is shown below.
Algorithm
Implementation
Explanation
-
Lines 1–10: The
partitionfunction takes a vectorAand an indexpas input. It selects a pivot elementA[p], moves it to the end of the array, and initializes two pointersiandj. It then scans the array from left to right withj, swapping any element less than the pivot withA[i]and incrementingi. Finally, it swaps the pivot element back to its sorted position,A[i]. The function then returns the indexiof the pivot element after it has been sorted. -
Lines 16–17: We select a pivot index
pin the middle of the array and partition the array using thepartitionfunction to obtain the pivot element’s sorted indexr. -
Lines 18–20: If
kis less thanr, it recurses on the left subarray from the beginning ofAtor. -
Lines 21–23: If
kis greater thanr, it recurses on the right subarray fromr + 1to the end ofA. -
Lines 24–25: If
kis equal tor, it returns the pivot element at indexr.
This algorithm has two important features. First, just like quick-sort, the correctness of quickselect does not depend on how the pivot is chosen. Second, even if we really only care about selecting medians (the special case ...