Sorting algorithms, step by step
Sorting is the first place most interviews go, because it exposes how you think about comparisons, swaps, and the cost of moving data. The visualizer above animates each comparison and swap so you can see why an O(n log n) algorithm pulls away from an O(n²) one as the array grows.
Watch for the shape of the work: Bubble and Insertion Sort do local, neighbour-by-neighbour fixes; Merge and Quick Sort split the problem and combine results. That structural difference — not the code length — is what the complexity column is really measuring.
Time and space complexity
| Algorithm | Best | Average | Worst | Space | Stable |
|---|---|---|---|---|---|
| Bubble Sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Insertion Sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Selection Sort | O(n²) | O(n²) | O(n²) | O(1) | No |
| Merge Sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quick Sort | O(n log n) | O(n log n) | O(n²) | O(log n) | No |
| Heap Sort | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
How to use this visualizer
Pick an algorithm from the track selector to load its pseudocode.
Step forward one operation at a time and watch the highlighted line move with the array state.
Note which bars are being compared versus actually swapped — comparisons dominate the count.
Re-run with a nearly-sorted array to see Insertion Sort collapse to O(n) while Selection Sort does not.
Frequently asked questions
For general-purpose arrays, Quick Sort is usually fastest in practice: it averages O(n log n) and its in-place partitioning is cache-friendly. That is why most standard libraries build on it — though real implementations switch to Insertion Sort for tiny sub-arrays and fall back to Heap Sort when recursion runs too deep, to avoid Quick Sort's O(n²) worst case.
Quick Sort partitions around a pivot in place, so it needs only O(log n) stack space, but a poor pivot degrades it to O(n²) and it is not stable. Merge Sort guarantees O(n log n) in every case and is stable, at the cost of O(n) extra space for merging. Choose Merge Sort when stability matters or when sorting linked lists; choose Quick Sort for in-memory arrays.
A stable sort preserves the relative order of elements that compare equal. If you sort records by city and then by name, a stable sort keeps the city ordering intact within each name group. Merge Sort and Insertion Sort are stable; Quick Sort, Heap Sort, and Selection Sort are not, unless you add a tiebreaker.
Any algorithm that only compares pairs of elements builds a decision tree whose leaves are the n! possible orderings. A binary tree with n! leaves has height at least log₂(n!), which is Θ(n log n). Counting Sort and Radix Sort beat this only because they read the values themselves rather than comparing pairs.