StringMash.com

Merge sort visualizer

Watch it split the list in half, sort the halves and merge them.

24 characters
Updates as you type
The animation is below

Show the steps
  1. Split 38 27 43 3 9 82 10 into 38 27 43 3 and 9 82 10.
  2. Split 38 27 43 3 into 38 27 and 43 3.
  3. Split 38 27 into 38 and 27.
  4. Merged: 27 38.
  5. Split 43 3 into 43 and 3.
  6. Merged: 3 43.
  7. Merged: 3 27 38 43.
  8. Split 9 82 10 into 9 82 and 10.
  9. Split 9 82 into 9 and 82.
  10. Merged: 9 82.
  11. Merged: 9 10 82.
  12. The two halves are merged.
  13. Sorted in 14 comparisons.

Watch it sort

  • Being compared
  • Just moved
  • In its final place
  • Not being worked on

Type a list above to see it sorted step by step.

Using the visualizer

Type a list in the box, separated by commas, spaces or new lines. Numbers are sorted by value and words alphabetically. The animation below plays the sort: the part of the list being worked on stays bright and the rest fades back, yellow bars are being compared, and orange marks the item that has just been placed.

Play, Step forward, Step back and Speed work as you'd expect. Show the steps lists every split and every merge in order. The animation takes up to 24 items.

How merge sort works

Merge sort splits the list in half, then splits each half in half again, until every piece is a single item. A single item is already sorted.

Then it merges the pieces back together in pairs. Merging two sorted lists is easy: look at the first item of each, take the smaller one, and repeat. When one list runs out, the rest of the other follows on. Pair by pair, the sorted pieces grow until there's one sorted list.

Why it's fast

Halving the list again and again takes about log₂ n rounds, and each round of merging looks at every item once. So merge sort makes on the order of n × log₂ n comparisons, written O(n log n). For a thousand items that's around 10,000 comparisons, where bubble sort can need nearly 500,000.

Merge sort is also stable: items that compare equal stay in the order they started in, which matters when sorting a table by one column after another.

Von Neumann's sort

Merge sort was invented by John von Neumann in 1945. A detailed description of the bottom-up version, which merges pairs, then fours, then eights, appeared in a report by Goldstine and von Neumann in 1948.

Questions

Is merge sort better than bubble sort?

For anything but tiny lists, yes. It needs far fewer comparisons as lists grow. The cost is extra memory to hold the pieces while merging.

What does stable mean?

Equal items keep their original order. Sort people by surname, and two Smiths stay in whatever order they were in before.

Why does the animation only go up to 3 steps a second?

Each step changes the colour of a bar or two, and three changes a second is the limit the web's accessibility guidelines set for anything that flashes. Step forward moves as fast as you can click.