Engineering A Sort Function

February 23, 2010

Scheme doesn’t provide pointers, so we use indexes into the vector. Swap! is a macro that causes its code to be inlined, in the spirit of the Bentley/McIlroy original. Where the original had the pivot selection in-line, we write pv-init and mid3 as functions to simplify the main body of the code. We store the pivot element in a[0], which is one of the options provided by the appendix. We perform an infinite loop with let loop (), and break out of the loop with an unless that calls (loop) but exits the loop if its condition is not satisfied. Otherwise, we have been very faithful to the Bentley/McIlroy original. Here is our solution:

As a test, we instrumented the code by adding a counter to the comparison function. Averaged over ten runs, sorting a vector with 220 = 1048576 random integers uses less than 1.1 n log n= 23068672 comparisons per run, as predicted by Bentley and McIlroy.