DEV Community

Cover image for Merge Sort vs Bubble Sort — Why 800 Comparisons Beats 147 Every Time
Amar Gul
Amar Gul

Posted on

Merge Sort vs Bubble Sort — Why 800 Comparisons Beats 147 Every Time

Most developers know Merge Sort is faster
than Bubble Sort. But watching it happen
makes the difference visceral.

The Numbers

Bubble Sort: 800+ comparisons
Merge Sort: 147 comparisons
Same 30 elements. Same result.

Why Such a Difference?

Bubble Sort compares adjacent elements
and moves them one step at a time —
O(n²) in worst case.

Merge Sort divides the array completely
down to single elements, then merges
them back in sorted order — O(n log n)
guaranteed every single time.

The Key Code

The entire algorithm is built on one
recursive insight:

\javascript
function mergeSort(arr, left, right) {
if (left >= right) return;
const mid = Math.floor((left + right) / 2);
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
\
\

A single element is already sorted by
definition. Everything else is just
merging sorted groups together.

Built in React — Zero Libraries

Animation state managed entirely with
useState and useRef. No external
animation libraries.

Color coding:

  • Purple = unsorted
  • Gold = currently merging
  • Red = comparing
  • Cyan = fully sorted

Watch It

What's Next

Quick Sort — the algorithm that actually
powers sorting in most programming
languages. Spoiler: it's faster than
Merge Sort in practice despite worse
worst-case complexity.

Subscribe to AlgoCanvas:
👉 youtube.com/@AlgoCanvas

Top comments (0)