Sorting Algorithm Visualizer

Seven sorting algorithms on the input of your choice, one frame at a time. The counters underneath show exactly how many comparisons and writes each one spends, so the difference between them is a number rather than a claim.

Sorting visualizerQuick sort · Random
Algorithm
Input
unsortedcomparingwritingin final position
0
comparisons
0
writes
0 / 16
in place

Quick sort: pick a pivot, move everything smaller to its left, then recurse on each side.

Step 1 of 78
Quick sort

Usually the fastest in practice thanks to cache behaviour, but the worst case is real without a good pivot.

best O(n log n)average O(n log n)worst O(n²)space O(log n)not stablein place
On this exact inputComparisonsWritesWorst case
Bubble sort117114O(n²)
Selection sort12026O(n²)
Insertion sort6972O(n²)
Merge sort4664O(n log n)
Quick sort4246O(n²)
Heap sort85112O(n log n)
Counting sort016O(n + k)

Counting sort runs on a smaller value range than the others, since it needs one bucket per distinct value.

How to use it

Common questions

Which sorting algorithm is the fastest?+

For general use, quick sort is usually fastest in practice because its inner loop is tight and cache-friendly, even though its worst case is O(n²). Merge sort matches it asymptotically and is stable but needs O(n) extra memory. Real language runtimes mostly use hybrids: Timsort in Python and Java for objects, and introsort (quick sort that falls back to heap sort) in C++.

What does it mean for a sort to be stable?+

A stable sort keeps equal elements in their original relative order. It matters whenever records are sorted by more than one field: sort by name, then stably by department, and within each department the names are still in order. Merge, insertion, bubble and counting sort are stable; quick, heap and selection sort are not.

Why can't any comparison sort beat O(n log n)?+

A comparison sort learns about the input only through yes/no comparisons, so a run of c comparisons can distinguish at most 2^c different orderings. There are n! possible orderings, so 2^c must be at least n!, which gives c ≥ log2(n!) ≈ n log n. Counting and radix sort get around this by not comparing elements at all.

When should I use insertion sort?+

On small arrays and on nearly-sorted data, where it runs in close to linear time. That is why production sorts switch to insertion sort once a partition drops below roughly 10 to 30 elements: at that size its low overhead beats the recursion of an asymptotically better algorithm.

What is the difference between comparisons and writes?+

A comparison asks which of two elements is larger; a write stores a value into the array. They are counted separately because they can cost very different amounts. Selection sort does O(n²) comparisons but only n-1 swaps, which makes it attractive when writing is expensive, such as to flash memory.

Learn the theory