Sorting Algorithm Visualizer
Animate bubble merge and quicksort algorithms
Updated
What is the Sorting Algorithm Visualizer?
A sorting algorithm visualizer turns abstract O(n²) and O(n log n) theory into something you can see. Every comparison, swap, partition, and merge is rendered as an animated bar chart with a highlighted, color-coded "active" element, a live pseudocode panel that follows the algorithm line-by-line, and a running tally of comparisons, swaps, and array accesses.
This tool runs eight classic sorting algorithms in your browser — Bubble, Selection, Insertion, Merge, Quick, Heap, Shell, and Cocktail Shaker — on five different input distributions (random, reversed, nearly-sorted, few unique values, or your own custom list).
Why visualize a sorting algorithm?
Big-O notation tells you that Bubble Sort is slower than Quick Sort, but it does not tell you why. A visualizer makes the mechanism obvious:
- Bubble Sort repeatedly swaps adjacent out-of-order pairs, and you can literally watch large values "bubble" to the end of the array one pass at a time.
- Selection Sort scans the entire unsorted suffix to find the minimum, then drops it into place — the comparisons look like a sliding window.
- Insertion Sort shifts each new key leftward until it fits, which is blindingly fast on nearly-sorted input.
- Merge Sort splits the array in half, sorts each half, then stitches them back together — the recursion is visible as nested working ranges.
- Quick Sort picks a pivot, partitions the array around it (smaller on the left, larger on the right), then recurses.
- Heap Sort builds a max-heap in place, then swaps the root to the end and sifts down.
- Shell Sort is insertion sort on widely-spaced elements, with the gap halving each pass.
- Cocktail Shaker Sort is bubble sort that sweeps in both directions, finishing faster on nearly-sorted data.
What you get
- Step-by-step scrubbing — pause, single-step forward, single-step backward, or jump to any point in the sort using a slider.
- Live operation counters — comparisons, swaps/writes, array accesses, and wall-clock time, all updating on every step.
- Pseudocode panel — the line currently executing is highlighted so you always know what the algorithm is doing.
- Complexity card — best / average / worst time complexity, space complexity, and whether the algorithm is stable or in-place.
- Five input presets including worst-case (reversed) and a custom-input box that accepts comma- or space-separated values.
- Keyboard shortcuts —
Spaceto play/pause,←/→to step,Rto reset. - 100% client-side — no accounts, no uploads, no servers. The largest arrays (150 elements) sort entirely in your browser.
Whether you are a student trying to internalize recursion, an instructor preparing a lecture, or a developer preparing for a coding interview, a sorting visualizer is the fastest way to feel the difference between an O(n²) quadratic and an O(n log n) divide-and-conquer algorithm.
How it works
This page breaks the tool into its three moving parts: the input layer (what data you feed in), the algorithm layer (how each sort is run), and the playback layer (how the animation is driven).
1. Generating an array
The visualizer works on a one-dimensional array of integers. You choose an array preset to control the initial distribution, and a size slider to set the length.
| Preset | Description | When it matters |
|---|---|---|
| Random | Uniform random integers in [5, 100] |
The "typical" case for benchmarks |
| Reversed | Strictly descending n, n-1, …, 1 |
The worst case for many O(n²) sorts |
| Nearly sorted | Ascending with ~10 % of pairs swapped | Reveals adaptive algorithms (insertion, cocktail) |
| Few unique | Only 4 distinct values | Highlights how partitioning behaves when many elements are equal |
| Custom | You type comma- or space-separated integers (0–9999, up to 200 values) | Visualize the sort on your own real data |
Click Apply preset to (re)generate the array, or Shuffle to randomize the current one in place.
2. Running the sort as a list of steps
Each of the eight algorithms is implemented as a JavaScript generator function. A generator is a function that can yield intermediate results and then resume — perfect for streaming a sequence of "snapshots."
For every step the algorithm takes, the generator yields a Step object containing:
- the current array (a copy, not a reference),
- the indices currently being compared (highlighted amber),
- the indices currently being swapped or written (highlighted red),
- the pivot index for partitioning algorithms (highlighted blue),
- the indices already finalized (rendered faded),
- the active working range for recursive algorithms (rendered with reduced opacity),
- the 1-based pseudocode line currently executing,
- the running totals of comparisons, swaps, and array accesses.
The generator is pure — it has no DOM, no React, no setTimeout. All of the playback, animation, and UI logic is handled by the React component that consumes the step list.
Because every step is a full snapshot, the UI can:
- play forward at a configurable speed,
- play backward one step at a time,
- scrub to any step with a slider,
- or jump straight to the end to inspect the final state.
3. Driving the animation
Three useEffect hooks cooperate to drive playback:
- Step generation — re-runs
runSort(algorithm, array)whenever the algorithm or input array changes. The result is stored in aStep[]and the index resets to0. The computation is deferred withsetTimeout(0)so the React render commits first and the UI never blocks on the (potentially expensive) sort. - Auto-advance — when
isPlayingistrue, asetTimeoutis scheduled to bump the step index by one. The delay is200 × 0.93^speedms, so speed1is ~200 ms per step and speed100is effectively 0 ms (RAF-bounded). - Wall-clock timer — a 50 ms
setIntervalupdates a live "elapsed time" stat while the sort is playing. The timer pauses cleanly when playback is paused, and resets to zero when you reset or regenerate the array.
A useRef pair (startedAtRef, accumulatedRef) tracks the current play segment so pause/resume keeps the elapsed time continuous.
4. The eight algorithms at a glance
| Algorithm | Best | Average | Worst | Space | Stable | In-place |
|---|---|---|---|---|---|---|
| Bubble Sort | O(n) |
O(n²) |
O(n²) |
O(1) |
✅ | ✅ |
| Selection Sort | O(n²) |
O(n²) |
O(n²) |
O(1) |
❌ | ✅ |
| Insertion Sort | O(n) |
O(n²) |
O(n²) |
O(1) |
✅ | ✅ |
| Merge Sort | O(n log n) |
O(n log n) |
O(n log n) |
O(n) |
✅ | ❌ |
| Quick Sort | O(n log n) |
O(n log n) |
O(n²) |
O(log n) |
❌ | ✅ |
| Heap Sort | O(n log n) |
O(n log n) |
O(n log n) |
O(1) |
❌ | ✅ |
| Shell Sort | O(n log n) |
O(n^1.5) |
O(n²) |
O(1) |
❌ | ✅ |
| Cocktail Sort | O(n) |
O(n²) |
O(n²) |
O(1) |
✅ | ✅ |
5. Reading the bar colors
| Color | Meaning |
|---|---|
| Dark (default) | Idle — not currently part of an active operation |
| Amber | Currently being compared to another bar |
| Red | Currently being swapped or written |
| Blue | The pivot element (Quick Sort partitions) |
| Faded dark | Finalized in its sorted position |
| Reduced opacity | Inside the active working range (merge / partition) |
The pseudocode panel on the right shows the same algorithm in plain English, with the line that is currently executing highlighted in dark.
6. Keyboard shortcuts
| Key | Action |
|---|---|
Space |
Play / pause |
→ |
Step forward |
← |
Step backward |
R |
Reset to step 0 |
Shortcuts are suppressed automatically while you are typing in a text input or interacting with a select.
Examples
Bubble sort a small random array
Run the classic O(n^2) algorithm on 10 random integers and watch each adjacent pair get compared and swapped.
Quick sort a reversed (worst-case) array
Pick a reversed 15-element array to expose the worst case of Lomuto-partition Quick Sort with the last element as the pivot.
Sort a custom array of values
Type your own comma-separated integers and run Merge Sort on them to see divide-and-conquer in action on real data.
Frequently asked questions
What is a sorting algorithm visualizer?
What is a sorting algorithm visualizer?
A sorting algorithm visualizer is an interactive tool that animates how different sorting algorithms (like Bubble Sort, Quick Sort, or Merge Sort) rearrange a list of values. It typically renders the array as a bar chart, highlights the elements being compared or swapped, and counts the number of operations the algorithm performs.
Which sorting algorithms can I visualize here?
Which sorting algorithms can I visualize here?
Eight: Bubble Sort, Selection Sort, Insertion Sort, Merge Sort, Quick Sort, Heap Sort, Shell Sort, and Cocktail Shaker Sort. Each one can be run on the same input so you can compare them directly.
What array presets are available?
What array presets are available?
Five presets: Random (uniform random integers), Reversed (worst case for many O(n²) algorithms), Nearly sorted (~10% of adjacent pairs swapped), Few unique values (only four distinct values), and Custom (you supply the list).
How large can the array be?
How large can the array be?
You can set the size anywhere from 5 to 150 elements with the size slider, or type up to 200 values in the custom-input box. The largest possible sort (150 elements through Bubble Sort) generates roughly 22,000 steps and runs entirely in your browser.
Can I use my own data?
Can I use my own data?
Yes. Choose the Custom preset, type comma- or space-separated integers (each between 0 and 9999), and click Apply preset. The parser accepts 1, 2, 3, 1 2 3, 1;2;3, and mixed separators, and it will reject empty input, non-numeric tokens, and values outside the allowed range with a clear error message.
How fast are the algorithms really?
How fast are the algorithms really?
It depends on the algorithm and the input size. As a rule of thumb:
- Bubble, Selection, Insertion, Shell, and Cocktail run in
O(n²)time on average — they are fine for small arrays and become slow above a few hundred elements. - Merge, Heap, and Quick run in
O(n log n)time on average and stay fast even on 100,000+ elements. Use the live operation counters (comparisons, swaps, array accesses) to confirm the theoretical complexity on your own data.
What is the difference between stable and in-place?
What is the difference between stable and in-place?
A sorting algorithm is stable if it preserves the relative order of equal elements. For example, if two rows have the same last_name, a stable sort will keep them in their original order. An algorithm is in-place if it uses O(1) extra memory — it sorts the array without allocating a second array.
| Algorithm | Stable | In-place |
|---|---|---|
| Bubble, Insertion, Merge, Cocktail | ✅ | varies |
| Quick, Heap, Shell, Selection | ❌ | ✅ |
Why is Quick Sort sometimes slow?
Why is Quick Sort sometimes slow?
Quick Sort has an average complexity of O(n log n), but its worst case is O(n²). The worst case happens when the pivot is consistently the smallest or largest remaining element — for example, picking the last element as the pivot on an already-sorted or reversed array. This tool uses the Lomuto partition scheme with the last element as the pivot, so try the Reversed preset to see the worst case in action.
Why does Merge Sort need extra memory?
Why does Merge Sort need extra memory?
Merge Sort is a divide-and-conquer algorithm: it recursively splits the array in half, sorts each half, and then merges the two sorted halves back together. The merge step needs a temporary buffer of size n to hold one of the halves while writing the merged result back. That is why its space complexity is O(n), while Quick Sort, Heap Sort, and Shell Sort are all in-place.
What do the bar colors mean?
What do the bar colors mean?
- Dark (default) — the bar is idle.
- Amber — the bar is currently being compared to another bar.
- Red — the bar is currently being swapped or written.
- Blue — the bar is the pivot (Quick Sort).
- Faded dark — the bar has reached its final sorted position.
- Reduced opacity — the bar is inside the active working range of a recursive algorithm (merge or partition).
Can I step through a sort manually?
Can I step through a sort manually?
Yes. Click Pause to stop the animation, then use Back and Forward to step one operation at a time. You can also drag the scrub slider to jump to any step in the sort. The pseudocode panel highlights the line that is executing at the current step.
Does the tool send my data to a server?
Does the tool send my data to a server?
No. Everything — array generation, sorting, and animation — runs 100% in your browser. There is no backend, no account, and no telemetry. You can disconnect from the internet after the page loads and the tool will still work.
Are there keyboard shortcuts?
Are there keyboard shortcuts?
Yes:
Space— play / pause→— step forward←— step backwardR— reset to step 0 Shortcuts are disabled automatically while you are typing in a text input or interacting with a select, so they will not interfere with the custom-array field.
Which algorithm should I use in production code?
Which algorithm should I use in production code?
For most general-purpose use cases, Quick Sort or Timsort (the hybrid algorithm used by Python, Java, and V8) is the best default. Quick Sort is fast in practice and in-place; Timsort is stable, adaptive, and has excellent worst-case behavior. Merge Sort is a better choice when you need guaranteed O(n log n) worst-case performance or stability. Heap Sort is the right pick when you need O(1) extra memory and a guaranteed O(n log n) bound.
What is the best way to learn sorting algorithms with this tool?
What is the best way to learn sorting algorithms with this tool?
A good study loop:
- Start with a small array (8–12 elements) and Bubble Sort or Insertion Sort. Step manually and watch the pseudocode line move in sync with the bars.
- Run the same array through a different algorithm (e.g. Quick Sort) and compare the comparison counts. The lower number is your "winner."
- Switch the preset to Reversed and run the same algorithm again. For
O(n²)sorts, you will see the worst case. - Try Nearly sorted with Insertion Sort or Cocktail Sort — both are adaptive and will finish much faster.
- As you grow comfortable, increase the size to 50–100 elements to feel the difference between quadratic and
O(n log n)algorithms.
Related tools
More utilities you might find handy.
Binary Search Visualizer
Visualize binary search algorithm step by step
Recursion Tree Visualizer
Visualize recursive call trees step by step
Regex Visualizer — Railroad Diagram Generator for Regular Expressions
Free online regex visualizer that renders any JavaScript regular expression as an interactive railroad diagram, with a plain-English breakdown, live match tester, and ReDoS warnings — all in your browser.