Hoare’s Partition, Improved
November 1, 2016
In today’s exercise we will make several improvements to the quicksort program of the previous exercise, working in small steps and measuring our progress throughout. We make the following improvements:
- Move the swap and comparison inline.
- Early cutoff and switch to insertion sort.
- Improved pivot with median-of-three.
All three improvements are well-known. The first improvement eliminates unneeded function-calling overhead. The second improvement reduces the number of recursive calls on very small sub-arrays, replacing them with a sorting algorithm that is well-adapted to nearly-sorted arrays. The third improvement improves the likelihood of a good partition and eliminates some cases where the algorithm performs poorly.
Your task is to write an improved quicksort and measure your improvement. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Here’s a solution in C99. Compiler optimizations were disabled. Each improvement was added successively. I didn’t look at how each one improves performance in isolation.
For each experiment, I sorted 50,000 random arrays, each with 1,000 elements.
The unoptimized version took 6.506 seconds.
Adding Inlined swapping reduced the time to 5.392 seconds.
Using insertion sort for arrays with 21 or fewer items reduced the time to 4.703 seconds. I manually tuned the size of arrays for early cutoff.
Adding median-of-three for determining a pivot reduced the time to 4.653 seconds.
The following code (and corresponding output) includes all the improvements.
Output:
[…] two previous exercises we’ve been working toward a variant of quicksort that has guaranteed O(n log n) performance; […]
[…] sorting algorithm that we have been working up to in three previous exercises is introspective sort, or introsort, invented by David Musser in 1997 for the C++ […]