Begin Algo
Sorting · Comparison

Sorting algorithms compared

Eight sorting algorithms side by side: time, space, stability, in-place or not, and, most importantly, when to reach for which.

AlgorithmTimeSpaceBestWorstStableIn placeDifficulty
Bubble SortBubble sortO(n²)O(1)O(n)O(n²)Intro
Selection SortSelection sortO(n²)O(1)O(n²)O(n²)Intro
Insertion SortInsertion sortO(n²)O(1)O(n)O(n²)Intro
Merge SortMerge sortO(n log n)O(n)O(n log n)O(n log n)Intermediate
Quick SortQuicksortO(n log n) averageO(log n)O(n log n)O(n²)Intermediate
Heap SortHeapsortO(n log n)O(1)O(n log n)O(n log n)Intermediate
Counting SortCounting sortO(n+k)O(n+k)O(n+k)O(n+k)Intermediate
Radix / Bucket SortRadix and bucket sortO(d·n)O(n+k)O(d·n)O(d·n)Intermediate

When to pick which

Choosing guide

  • No idea: the language's built-in sort. It is usually Timsort (Python, Java objects) or introsort (C++), which already blend merge, insertion and heap for you.
  • Ties must keep their order: the stable ones — merge, insertion, counting, radix. Quick and heap sort are not stable.
  • Keys are small integers: counting or radix sort, the only way past the n log n lower bound, because they never compare.
  • Nearly sorted: insertion sort in O(n). Bubble sort with early exit works too, but degrades when a small value sits at the end.
  • Memory is tight: heap sort (O(1) extra, guaranteed n log n) or quicksort (O(log n) stack). Merge sort needs a second O(n) buffer.
  • Data does not fit in memory: merge sort — read a chunk, sort it, write it out, then k-way merge the runs.