Data Structures & Algorithms / Module 4: Searching and sorting

Topic 4.5

Quick sort

Partitioning around a pivot: fast and memory-light, as long as the pivot isn't bad.

10 min · intermediate

Watch: one number is chosen as the marker. Smaller ones gather on its left, and the marker lands in its final place.

0123456758291637
  • moving now
  • being checked
  • passed / marked
  • finished / the result
Step 1 of 26

Quick sort: pick a pivot, put smaller numbers on its left and bigger ones on its right, then repeat for each side.

Every partition puts one pivot in its final place. An even split is fast; a pivot that is always the largest is slow.
data:

Like splitting a class by height

A teacher picks one pupil and says: "shorter than them, go left; taller, go right." That pupil is now standing in the right spot, even though both groups are still jumbled. Do the same inside each group, and the groups get smaller until everyone is in order. This splitting step is called a partition.

Code, for programmersQuick sort, pivot = last element
function quickSort(a, lo = 0, hi = a.length - 1) {
  if (lo >= hi) return a;
  const pivot = a[hi];
  let i = lo;                          // a[lo..i-1] are smaller than pivot
  for (let j = lo; j < hi; j++) {
    if (a[j] < pivot) {
      [a[i], a[j]] = [a[j], a[i]];
      i++;
    }
  }
  [a[i], a[hi]] = [a[hi], a[i]];       // pivot goes to its final spot
  quickSort(a, lo, i - 1);
  quickSort(a, i + 1, hi);
  return a;
}

When it is fast, when it is slow

If the pivot splits the list into roughly equal halves, it's the same story as merge sort: log n levels, n steps per level, n log n in total. In practice quick sort is often faster than merge sort because it works inside the same array and is cache-friendly.

But choose "already sorted" in the figure. The pivot is always the largest number, so every partition sets aside just one number. There are n levels instead of log n, and the total is about n²/2. Sorted data is very common in real life, so this is a real problem.

Quiz

  1. After one partition, what is certainly true about the pivot?

  2. Quick sort with the last element as pivot is given an already sorted list. What does it cost?

  3. A common way to avoid quick sort's worst case?

0 of 3 answered.