Study Atlas › Computer Science › Algorithms

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

Sorting [5,2,9,1]: quicksort with pivot 5 gives [2,1] + [5] + [9], then [1,2,5,9].

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

  1. Pick a pivot
  2. Partition items into less, equal and greater
  3. Recursively sort the partitions
  4. Concatenate results

Open the interactive page with diagrams →

People behind it

References

  1. C. A. R. Hoare, Comput. J. 1962, 5, 10–16.

Textbooks

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