Quicksort Study Guide

Partitioning. Partioning an array on a pivot means to rearrange the array such that all items to the left of the pivot are less-than-or-equal to the pivot, and all items to the right are greater-than-or-equal to the pivot. There are several partitioning strategies: know how to execute 3-scan partitioning (allocate a new array) and Hoare partitioning.

Hoare Partitioning. One very fast in-place technique for partitioning is to use a pair of pointers that start at the left and right edges of the array and move towards each other. The left pointer loves small items, and hates equal or large items, where a “small” item is an item that is smaller than the pivot (and likewise for large). The right pointers loves large items, and hates equal or small items. The pointers walk until they see something they don’t like and, once both have stopped, they swap items. After swapping, they continue moving towards each other, and the process completes once they have crossed. In this way, everything left of the left pointer is less-than-or-equal to the pivot, and everything to the right is greater-than-or-equal to the pivot. Finally, we swap the pivot into the appropriate location, and the partitioning is completed. Unlike our 3-scan partitioning, this partitioning strategy results in a sort which is measurably faster than mergesort.

Pivot Selection. Choice of partitioning strategy and pivot have profound impacts on runtime. Two pivot selection strategies that we discussed: use the leftmost item and approximate median-of-3. Understand how using leftmost item can lead to bad performance on real data.

Quicksort. Partition on some pivot. Quicksort to the left of the pivot. Quicksort to the right. Understand how to show the best case and worst case for quicksort, which depends on the choice of pivot item and partitioning algorithm.

  1. One strategy to speeding up quicksort is to insertion sort subarrays of size approximately 10 or smaller. An alternate approach is to simply not sort arrays of size less than 10 and then use insertion sort on the entire array. Show that this alternate approach results in a linear time sort, despite insertion sort’s quadratic time worst case.
  2. Q2b from CS 61B 18sp Final (Solution)
  3. Q8a from CS 61B 18sp Final (Solution)