Engineering a Sort Function
Jim Royer
CIS 351
February 4, 2019
Royer (CIS 351) Engineering a Sort Function February 4, 2019 1 / 16
Bentley and MacIlroy, 1993 Engineering a Sort Function
JON L. BENTLEY
- M. DOUGLAS McILROY
AT&T Bell Laboratories, 600 Mountain Avenue, Murray Hill, NJ 07974, U.S.A. SUMMARY We recount the history of a new qsort function for a C library. Our function is clearer, faster and more robust than existing sorts. It chooses partitioning elements by a new sampling scheme; it partitions by a novel solution to Dijkstra’s Dutch National Flag problem; and it swaps efficiently. Its behavior was assessed with timing and debugging testbeds, and with a program to certify performance. The design techniques apply in domains beyond sorting.
From: Software Practice and Experience, Vol. 23 (1993) 1249–1265.
http://www.skidmore.edu/~meckmann/2009Spring/cs206/papers/spe862jb.pdf
Royer (CIS 351) Engineering a Sort Function February 4, 2019 2 / 16
Why rewrite Unix’s quicksort?
In ancient days of yore (≈ 1991): The old quicksort (qsort) had be in use for ≈ 20 years and was stable and usually fast. A colleague found that qsort ran in Θ(n2) time inputs with certain structures, e.g., on pipe-organ arrays of 2n integers: 1,2,3,4,...,n,n,...,4,3,2,1. They found that all the then competitors of qsort could also be driven to Θ(n2) on certain reasonable inputs. “Users complain when easy inputs don’t sort quickly.” So it was time for a new systems-level quicksort.
Royer (CIS 351) Engineering a Sort Function February 4, 2019 3 / 16
Bentley and MacIlroy’s version of CLRS’s Quicksort
void iqsort0(int *a, int n) { int i, j; if (n <= 1) return; for (i = 1, j = 0; i < n; i++) if (a[i] < a[0]) swap(++j, i, a); swap(0, j, a); iqsort0(a, j); iqsort0(a+j+1, n-j-1); }
Program 2. A toy Quicksort, unfit for general use
more efficient (and more familiar) partitioning method uses
On nearly sorted arrays, the above makes ≈ n2 2 many comparisons!
Royer (CIS 351) Engineering a Sort Function February 4, 2019 4 / 16