Skip to content

Implementing and improving a sorting routine

Question

Code up a sorting algorithm of your choice, analyse its running time and memory use, and then suggest improvements.

Short answer

A good choice is quicksort: average O(nlog⁡n)O(n\log n) time, O(log⁡n)O(\log n) stack, but O(n2)O(n^2) worst case. Partition around a pivot and recurse on both sides. Improve with median-of-three or random pivots, three-way partitioning for duplicates, insertion sort on small subarrays, recursing on the smaller side first, and falling back to heapsort when depth grows (introsort). Merge sort guarantees O(nlog⁡n)O(n\log n) and stability at the price of O(n)O(n) extra memory.

Adapted from Joshi, Denson & Downes, Quant Job Interview Questions and Answers, Q7.17, p.226; question and answer rewritten by SelfMadeQuant.com.

See the hint and the full worked solution in the question bank (free account).

Open the worked solution

Lessons behind this question