Sorting Algorithms

How Merge Sort Works

  • Waiting
  • Being compared
  • Just moved
  • In final position
1/50

Merge sort, 12 values in random order.

Settings

More options
Starting order

Two to 48 numbers, used in the order you type them.

Merge Sort

  1. 1width = 1
  2. 2while width < n:
  3. 3 for lo in 0..n step 2*width:
  4. 4 mid = lo + width
  5. 5 hi = lo + 2*width
  6. 6 // merge a[lo..mid) and a[mid..hi)
  7. 7 take the smaller head each time
  8. 8 width *= 2

How the Seven Compare

AlgorithmBestAverageWorstExtra memoryStable
BubbleO(n)O(n²)O(n²)O(1)Yes
InsertionO(n)O(n²)O(n²)O(1)Yes
SelectionO(n²)O(n²)O(n²)O(1)No
ShellO(n log n)O(n√n)O(n²)O(1)No
MergeO(n log n)O(n log n)O(n log n)O(n)Yes
QuickO(n log n)O(n log n)O(n²)O(log n)No
HeapO(n log n)O(n log n)O(n log n)O(1)No

Scroll the table sideways for the rest of the columns.

Stable means equal values keep their original order.