Sorting algorithms (quicksort, mergesort, heapsort)
Methods to put items in order; comparison sorts cannot beat O(n log n) in the worst case.
Edited by Alex C, EduAlx · Sources cited below
Explanation
Mergesort (von Neumann, 1945) divides, sorts halves and merges: O(n log n), stable. Quicksort (Hoare, 1959–61) partitions around a pivot: O(n log n) on average, O(n²) worst case, fast in practice. Heapsort is in-place O(n log n). Python and Java use Timsort, a hybrid of merge and insertion sort.
Example
Code
def quicksort(a):
if len(a) <= 1: return a
p = a[len(a)//2]
return (quicksort([x for x in a if x < p])
+ [x for x in a if x == p]
+ quicksort([x for x in a if x > p]))
How it works, step by step
- Pick a pivot
- Partition items into less, equal and greater
- Recursively sort the partitions
- Concatenate results
Open the interactive page with diagrams →
People behind it
- Tony Hoare (b. 1934), Computer science, UK: Invented quicksort, Hoare logic and CSP. Turing Award 1980.
- John von Neumann (1903–1957), Mathematics and computing, Hungary / USA: Worked on game theory, quantum mechanics foundations, the stored-program computer architecture, and cellular automata.
- Tim Peters
References
- C. A. R. Hoare, Comput. J. 1962, 5, 10–16.
Textbooks
- Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein (MIT Press, 4th ed. 2022). 'CLRS', the standard algorithms text.
- The Art of Computer Programming (Vols. 1–4B), Donald E. Knuth (Addison-Wesley, 1968–2023). Monumental work on algorithms.
- Algorithms, Robert Sedgewick, Kevin Wayne (Addison-Wesley, 4th ed. 2011). Practical algorithms with Java code.
Related topics
Graph algorithms: BFS, DFS and Dijkstra's shortest pathAlgorithms and Big-O complexityDynamic programmingString algorithms and pattern matchingGreedy algorithms and minimum spanning treesData structures: arrays, linked lists, stacks, queuesHash tablesError-detecting and error-correcting codesTrees and binary search treesHuman–computer interaction and usability