Skip to content
Data Structures and Algorithms / Linear Structures, Hashing, and the Sorting Toolkit

Medians and Order Statistics: Quickselect

Finding the median return in a dataset, or the 95th-percentile latency in a set of measurements, is the selection problem: find the kk-th smallest element of nn unordered elements. The obvious approach — sort everything, then read off index kk — costs Θ(nlog⁡n)\Theta(n\log n), but selection is a strictly easier problem than full sorting, and this note shows it can be solved in expected linear time by reusing quicksort's partition subroutine in a new way: quickselect. It closes with a pointer to a worst-case-linear algorithm (median-of-medians) for when the expected-time guarantee is not enough.

In this lesson

  1. Learning objectives
  2. The selection problem
  3. Quickselect
  4. Worst-case-linear selection: median-of-medians

Before you start

The full lesson, with worked examples and exercise solutions, is for members.

Read the full lesson

New to SelfMadeQuant.com? See membership options or explore the curriculum.