Quick Sort
1 Background
1.1 History
- Quicksort was contributed by Hoare in 1962. Hundreds of subsequent
papers!
- Over the decades of teaching, we "know" that only a few students
understand Quicksort. Why? Bad teaching? Poor student?
1.2 Optimal Sorting
- For an array of size n, the best we can do is O(n lg n).
Quicksort and Heapsort are both O(n lg n).
- Our interest is not in the perf analysis. Nor in the performance
itself.
1.3 Relevance to SE
- This is a good example to extrapolate to Software Engineering
issues.
1.4 Specs
- Signature: Quicksort(lo, hi).
- Array to be sorted: A[] of integers. Low index 1, high index n.
Global. Quicksort(1, n). n >= 1.
- Notation: A[lo .. hi] stands for the set of elements A[lo], .., A[hi].
- Pre:: true;;
- Post::
- hi >= lo and sorted(A, lo, hi) and permuted(A.old, A, lo, hi),
or
- hi < lo and A[] is unchanged, i.e., equal(A.old, A, lo, hi).
2 Partitioning Idea
- Quicksort(lo, hi). Focus only on A[lo] .. A[hi]. Assume hi >= lo.
Leave other elements of A[] untouched.
- Pick a value z := A[x], lo >= x >= hi. (The choice of z has an
impact on performance.)
- Permute the elements of A[] so that any A[lo .. p] <= z < any A[p+1
.. hi].
- permuted(A.old, A, lo, hi),
- p may equal lo - 1 (so A[lo .. p] is empty),
- p may equal hi (so A[p+1 .. hi] is empty),
- Quizz: At the end of the above, is A[x] equal to z?
- Then do
- Quicksort(1, p)
- Quicksort(p+1, n)
- All of this is elegantly discussed in (cite) [Foley and Hoare 1971].
4 References
- Hoare, Charles AR. "Quicksort." The Computer Journal 5.1 (1962):
10-16. https://comjnl.oxfordjournals.org/content/5/1/10.full.pdf.
Hoare is a Turning Award winner. Required Reading.
- Foley, Michael, and Charles Antony Richard Hoare. "Proof of a
recursive program: Quicksort." The Computer Journal 14.4 (1971):
391-395. Recommended Reading.
- Sedgewick, R. Quicksort Ph. D. Dissertation, Advisor: Donald Knuth,
Computer Science Dept., Stanford University (May 1975) Report
STAN-CS-75-492, 1975. Reference.
- Sedgewick, Robert, and Jon Bentley. "Quicksort is optimal."
Knuthfest, Stanford University, Stanford
(2002). https://www.cs.princeton.edu/~rs/talks/QuicksortIsOptimal.pdf
Recommended Reading.
- Bentley, Jon L., and M. Douglas McIlroy. "Engineering a sort
function." Software: Practice and Experience 23.11 (1993):
1249-1265.
- http://bigocheatsheet.com/ [Big-Oh Cheatsheet] Know Thy
Complexities! Includes "Array Sorting Algorithms". Highly
Recommended Visit.
- http://algs4.cs.princeton.edu/lectures/23Quicksort.pdf From the
book by Sedgewick and Wayne. Highly
Recommended Visit.