COMPUTER SCIENCE · School · College

Comparison-Based Sorting Visualizer

Can Bubble sort finish before Quick sort? On already sorted input, an early-exit Bubble sort needs one pass while a poor Quick-sort pivot can cause quadratic work. Compare seven actual implementations on identical data and discover why the input and the implementation matter.

↓ Jump to simulatorFree · No loginReal-time controlsUnits & models explained
LIVE EXPERIMENTReady · Press Start
Your browser does not support canvas. Read the scientific lesson below.
Press Start to explore the model

Implementation scope: Ascending sort of 8–64 integer keys from 0 through 99. Random inputs are deterministic for a given dataset number. This lab uses early-exit Bubble, swapping Selection, stable shift-based Insertion, top-down buffered Merge, last-element-pivot Lomuto Quick, max-heap Heap and halving-gap Shell. Instrumentation, animation and auxiliary readouts are not included in textbook space bounds. No wall-clock speed ranking is claimed.

Comparison-Based Sorting Visualizer — static example view
Example view of this experiment. Use the simulator above to explore your selected parameters and live measurements.
LEARNING OUTCOMES

What will you understand?

  • Trace comparisons, swaps and writes instead of memorizing an animation.
  • Distinguish algorithm growth rates from the time a browser takes to animate.
  • Explain why input order, pivot choice and extra storage change a sorting strategy.
  • Use original record positions to investigate stable and unstable sorting.
THE ALGORITHMS EXPLAINED

How the simulation works

Predict first, then compare

Choose two algorithms and keep the dataset number, array size and input pattern unchanged. Both lanes start with exactly the same keys. Start advances each lane at the selected number of recorded events per second; Step advances one event in each unfinished lane. A lane may spend an event comparing two keys, moving records or copying a buffer. The faster animation therefore has fewer recorded teaching events, not necessarily a faster compiled implementation.

What the counters measure

A comparison means comparing two key values. A swap performs two writes to the main array. Insertion and merging can perform individual writes without a swap. Auxiliary writes count recorded writes to temporary buffers; they exclude scalar assignments, memory allocation, loop tests and display work. One buffer-copy event can represent several auxiliary writes. During a shift or merge, the main array can temporarily repeat a key because another record is being held in a variable or buffer. The final result must preserve every original record.

Why comparison sorting has a lower bound

With distinct keys there are n! possible input orders. A yes/no comparison supplies one branch of a decision tree, so a correct comparison sorter needs enough leaves to distinguish these orders. Some input requires at least ceiling(log₂(n!)) comparisons. This gives a worst-case Ω(n log n) lower bound; it does not say that every input is difficult, or that every comparison algorithm reaches the bound. Algorithms that inspect digits or use keys as array addresses work under additional assumptions.

Stability is about equal keys

Imagine sorting student records by score while preserving their previous alphabetical order for equal scores. A stable algorithm retains the relative order of equal keys. Open the current-values readout: #1, #2 and so on identify the original records. Equal heights alone cannot demonstrate stability. Our Bubble, Insertion and Merge implementations are stable; Selection, last-pivot Quick, Heap and halving-gap Shell do not guarantee it.

ALGORITHM FIELD GUIDE

Choose a strategy, then trace its work

Properties of the specific implementations in this lab
AlgorithmWork boundExtra spaceStable?
Bubble sortBest Θ(n); worst Θ(n²)O(1)Yes
Selection sortΘ(n²) comparisons on every inputO(1)No
Insertion sortBest Θ(n); worst Θ(n²)O(1)Yes
Merge sortΘ(n log n) work in this versionO(n) auxiliary storageYes
Quick sortExpected Θ(n log n) for random distinct permutations; worst Θ(n²)O(log n) expected stack; O(n) worstNo
Heap sortO(n log n) worst-case workO(1)No
Shell sortO(n²) worst-case bound for these halving gapsO(1)No

Space bounds describe the sorting algorithm, excluding this visualizer's display and instrumentation. In the formulas, n is the number of records; k is the key range; b is the radix base; d is the number of digit passes; B is the bucket count and mᵢ is the size of bucket i.

Bubble sort

Scan neighboring records and swap only when the left key is larger. After a full pass, a largest remaining key has reached the right boundary, so the next pass can be shorter. This version remembers whether a swap occurred and stops when a pass makes none. That small implementation detail is why sorted input finishes quickly. Equality never causes a swap, preserving the order of ties.

Small example: On [3, 1, 2], swapping 3 with 1 gives [1, 3, 2]; swapping 3 with 2 gives [1, 2, 3]. A final shortened pass confirms the order.

for each shrinking unsorted prefix:
  changed = false
  compare adjacent keys
  swap inverted pairs; set changed = true
  stop if changed is false

Watch for: Select sorted and reversed patterns with the same size. Look for a linear versus quadratic comparison count.

Try Bubble sort in the simulator ↑

Selection sort

Find a minimum in the remaining suffix and swap it into the next output position. The search still visits every remaining candidate even when the input is already sorted. There are n(n−1)/2 key comparisons but at most n−1 nontrivial swaps in this implementation. A distant swap can move one equal-key record past another, so this variant is not stable.

Small example: Give the first two keys identities in [2a, 2b, 1]. Swapping the minimum into the first position produces [1, 2b, 2a]; the equal twos have reversed order.

for position i before the last:
  find minimum index in suffix i..end
  swap it with i if the indices differ

Watch for: Compare with Insertion on nearly sorted data. A low write count does not remove Selection's repeated scans.

Try Selection sort in the simulator ↑

Insertion sort

Maintain a sorted prefix. Hold the next record, shift larger prefix keys one position right, then insert the held record into the gap. Only strictly larger keys are shifted, so equal keys retain their order. The number of shifts reflects how many inversions the input contains. Nearly sorted data can therefore require much less work than reversed data.

Small example: In [1, 4, 3, 2], hold 3, shift 4 and insert 3 to get [1, 3, 4, 2]. Inserting 2 then shifts both 4 and 3.

for each key after the first:
  hold that record
  shift larger prefix keys to the right
  write the held record into the gap

Watch for: An intermediate repeated value is a shift in progress: the missing record is held temporarily.

Try Insertion sort in the simulator ↑

Merge sort

Recursively sort two halves, copy their records into buffers, then repeatedly write the smaller next key back to the main array. On equal keys, taking the left buffer first makes this version stable. Each level processes the records and the balanced division has logarithmic depth. Predictable growth comes with extra storage and buffer movement; the auxiliary-write counter makes that tradeoff visible.

Small example: Merging [1, 4] and [2, 3] compares 1 with 2, then 4 with 2, then 4 with 3. The remaining 4 is copied without another key comparison.

sort left half; sort right half
copy both halves to buffers
write the smaller next buffered key
on ties, take left; copy any remainder

Watch for: A merge comparison can involve buffered values. Read the operation text instead of assuming both values still occupy their original main-array positions.

Try Merge sort in the simulator ↑

Quick sort

This deliberately simple variant uses the last key as pivot and a Lomuto partition: keys less than or equal to it are moved to the left side. The pivot is placed at its final position and both sides are sorted recursively. Sorted, reversed and all-equal input can create extremely unbalanced partitions. Other pivot rules, randomized choices and three-way partitioning can behave very differently; the lab does not represent every production Quick sort.

Small example: For [3, 1, 2], the pivot is 2. The value 1 moves left, then the pivot swap produces [1, 2, 3]. On [1, 2, 3], the last pivot is already largest and leaves a smaller prefix to sort.

choose last key as pivot
scan other keys; partition keys ≤ pivot left
place pivot between the partitions
recursively sort both partitions

Watch for: Use Sorted input surprise to see the consequence of a pivot rule, not proof that Quick sort is always slow.

Try Quick sort in the simulator ↑

Heap sort

Build a max heap, where each parent is at least as large as its children. Swap the root with the last unsorted position, shrink the heap and sift the new root down. The maximum is repeatedly removed into a growing sorted suffix. Building the heap bottom-up takes linear work; repeated removals give the logarithmic factor. Swaps across distant positions do not preserve ties.

Small example: A max heap for [1, 3, 2] can be [3, 1, 2]. Move 3 to the end, repair the remaining heap, then remove 2.

build max heap bottom-up
while heap has more than one record:
  swap root with last heap record
  shrink heap and sift root downward

Watch for: The bars remain an array view. Parent/child positions follow indices 2i+1 and 2i+2; they need not be neighbors on screen.

Try Heap sort in the simulator ↑

Shell sort

Perform insertion sorts on interleaved subsequences separated by a gap. The lab starts at floor(n/2), halves the gap and finishes at one. Early passes can move records long distances before the final ordinary insertion pass. Performance depends strongly on the chosen gap sequence, so a complexity claim for another sequence must not be assigned to this implementation. Long-distance moves can reorder equal keys.

Small example: With eight keys the gaps are 4, 2 and 1. At gap 4, positions 1 and 5 belong to one subsequence; positions 2 and 6 belong to another.

gap = floor(n / 2)
while gap ≥ 1:
  insertion-sort each gap-spaced subsequence
  gap = floor(gap / 2)

Watch for: Watch which indices light up during early passes. They can be several columns apart.

Try Shell sort in the simulator ↑

Explore Non-Comparison Sorting Visualizer →

GROWTH & COST MODEL
Comparison lower bound: worst case Ω(n log n) for arbitrary distinct keys

Use the controls above to change the relevant parameters. All displayed values follow the assumptions stated on this page.

TRY IT YOURSELF

Three experiments to try

  1. Load Sorted input surprise. Predict the comparison counts for 32 keys, run to completion and compare Bubble against the last-element-pivot Quick implementation. Then repeat with reversed input.
  2. Compare Insertion and Selection with nearly sorted input. Keep the dataset number fixed while increasing size from 16 to 32. Explain which algorithm can take advantage of an already ordered prefix.
  3. Choose many duplicates and an array of eight keys. Step through Merge and Selection, opening the record readout. Compare the order of original-position labels for equal keys after completion.
WORKED EXAMPLE

Calculate it before you visualize it

For eight already sorted keys, early-exit Bubble compares seven adjacent pairs, performs zero main-array writes and stops. Selection still compares 7 + 6 + 5 + 4 + 3 + 2 + 1 = 28 pairs. Our Quick implementation always picks the last key as pivot. On sorted distinct input each partition leaves one subproblem shorter by only one, so it also makes 28 key comparisons. On eight distinct keys in reverse order, insertion sort makes 28 comparisons, 28 shift writes and seven writes of held keys: 35 main-array writes. These are counts for the stated implementations, not universal timings for algorithms with the same names.

QUICK KNOWLEDGE CHECK

Can you predict the result?

Does O(n log n) guarantee that Merge sort performs fewer operations than Insertion sort on every array?

Reveal the answer

No. Asymptotic bounds describe growth, not a fixed ranking for every input and size. Insertion can do linear work on sorted input and can have small overhead on short arrays. A buffered Merge implementation still divides and merges the data. The relevant work also depends on whether you count comparisons, writes, auxiliary storage or actual runtime.

ASSUMPTIONS & LIMITS

What the model does not show

Ascending sort of 8–64 integer keys from 0 through 99. Random inputs are deterministic for a given dataset number. This lab uses early-exit Bubble, swapping Selection, stable shift-based Insertion, top-down buffered Merge, last-element-pivot Lomuto Quick, max-heap Heap and halving-gap Shell. Instrumentation, animation and auxiliary readouts are not included in textbook space bounds. No wall-clock speed ranking is claimed.

REAL-WORLD CONNECTIONS

Where sorting is useful

Sorting helps prepare search indexes, arrange reports and organize records before grouping equal keys. Production libraries often combine strategies and choose pivot rules or run detection more carefully than a minimal teaching implementation. A stable sort is useful when later sorting passes should preserve a prior order among ties. Use this lab to explain those tradeoffs, then measure a real workload before choosing a library routine.

WATCH OUT

Common misconceptions

  • Quick sort is always the quickest: pivot selection, duplicate handling and input distribution matter.
  • Few swaps mean little work: Selection can perform few swaps while still making quadratic comparisons.
  • A green final array proves stability: identity labels are needed to distinguish equal-key records.
  • An in-place algorithm uses no memory at all: temporary variables and sometimes recursion still require storage.
  • All Shell sorts have the same complexity: their gap sequences are part of the algorithm.
CLASSROOM CHALLENGE

Try it with a class

Give each group the same dataset number and ask for predictions before running. Collect comparisons, main writes and auxiliary writes separately. Ask students to justify a surprising result using the specific implementation rather than a slogan such as Quick is fastest. For a written exercise, have them implement one method and reproduce the eight-key worked example. Discuss how the conclusion changes when comparisons are expensive or memory is constrained.

REFERENCES & MODEL REVIEW

Algorithm sources

MG Labs implements the specific variants described above. Automated tests check sorted order, record preservation, stability and selected exact operation counts. Reference implementations may use different pivots, gaps, bases or optimizations.

Princeton Algorithms — sorting performance and stability reference ↗

Princeton — Elementary Sorts ↗

MIT OpenCourseWare — comparison lower bounds, counting and radix sorting ↗

Model implementation: MG Labs teaching model. Independent subject-matter review and classroom testing are still pending.