Quicksort

These demos are intended to supplement (not replace!) Chapter 7 of Sedgewick's Algorithms book. You can find detailed descriptions, code, and other information about the algorithms in the book.

Each demo is a dynamic representation of the algorithm in action, sorting an array a containing a permutation of the integers 1 through N. For each i, the array element a[i] is depicted as a black dot plotted at position (i, a[i]). Thus, the end result of each sort is a diagonal of black dots going from (1, 1) at the bottom left to (N, N) at the top right. Each time an element is moved, a green dot is left at its old position. Thus the moving black dots give a dynamic representation of the progress of the sort and the green dots give a history of the data-movement cost.

Quicksort illustrates the operation of the basic algorithm. When the array is partitioned, one element is in place on the diagonal, the left subarray has its upper corner at that element, and the right subarray has its lower corner at that element. The original file is divided into two smaller parts that are sorted independently. The left subarray is always sorted first, so the sorted result emerges as a line of black dots moving right and up the diagonal.

Nonrecursive quicksort is the same, but always sorts the smaller of the two subfiles first, so as to limit the size ofthe recursive stack to be logarithmic in th file size.

Quicksort with median-of-3 partitioning and cutoff for small files samples the file to get an estimate for the partitioning element that is likely to be near the middle, and skips small files to be sorted in a final insertion sort pass. These improvements speed up the algorithm significantly.

3-way quicksort