Sorting algorithm visualizer
Watch six sorting algorithms work on the same data, step through each comparison and swap, and compare how much work they do.
What the colours mean
- Amber bars are being compared.
- Red bars are being swapped or written.
- Green bars are in their final position.
- Use Step to advance one comparison at a time, and the counters to compare how much work each algorithm does on the same data.
The algorithms
- Bubble sort swaps neighbours that are out of order; after each pass the largest remaining value has bubbled to the end. O(n²), but stops early if a pass makes no swaps.
- Selection sort finds the smallest remaining value and puts it next. Always O(n²) comparisons but at most n swaps.
- Insertion sort grows a sorted prefix by sliding each new value left into place. Very fast on nearly sorted data, which is why real libraries use it for small runs.
- Merge sort splits the list in half, sorts each half and merges them. Always O(n log n) and stable, at the cost of extra memory.
- Quick sort partitions around a pivot (here the last element) and recurses. O(n log n) on average and very fast in practice; already sorted input is its worst case with this pivot.
- Heap sort builds a max-heap, then repeatedly moves the largest value to the end. O(n log n) with no extra memory, but not stable.
Try these experiments
- Sort 64 bars with bubble sort, then with merge sort, and compare the comparison counts.
- Type an already sorted list such as 1, 2, 3, 4, 5, 6, 7, 8 and run insertion sort, then quick sort. One finishes almost instantly; the other hits its worst case.
- Enter repeated values like 3, 1, 3, 2, 1 to see how each algorithm handles duplicates.
Questions
Which sorting algorithm is the fastest?
For general data, O(n log n) algorithms such as merge sort, quick sort and heap sort. Quick sort is usually fastest in practice; insertion sort wins on small or nearly sorted lists.
What is the time complexity of bubble sort?
O(n²) comparisons in the average and worst case, and O(n) in the best case when the list is already sorted and no swaps happen.
What is a stable sort?
A sort that keeps equal values in their original order. Merge, insertion and bubble sort are stable; quick sort and heap sort as shown here are not.
Can I visualise my own data?
Yes. Type up to 200 positive numbers separated by commas into the box and they become the bars.
Where can I learn more algorithms?
Each algorithm links to a full explanation on this site, and DSA Master for iPhone covers 50+ data structures and algorithms with interactive visualizations.
From the same developer
- DSA Master: 50+ data structures and algorithms, visualised.
- Data structures and algorithms explained.