Home › Developer Tools › Sorting Algorithm Visualizer

Sorting Algorithm Visualizer

Watch seven classic sorting algorithms rearrange an array bar by bar. Follow the highlighted pseudocode line, count comparisons, swaps and writes, slow down to single steps, or race all seven on the same data to see Big-O complexity in action.

Last updated:

Comparisons0
Swaps0
Array writes0
Steps0
StatusReady
Use my own numbers

Up to 250 non-negative whole numbers (0 to 9999), separated by commas or spaces.

Advertisement
Advertisement

How to use the Sorting Algorithm Visualizer

  1. Pick an algorithm and the kind of starting data (random, nearly sorted, reversed or few unique values).
  2. Set the array size and speed with the sliders. Small arrays show each value above its bar.
  3. Press Start to animate, Step (or the right arrow key) to advance one operation, or Finish instantly to see the final counts.
  4. Follow along in the pseudocode panel: the current line is highlighted and the sentence below explains the operation.
  5. Press Race all algorithms to run every algorithm on the same array and compare how many steps each one needs.

Sorting algorithm complexity cheat sheet

AlgorithmBestAverageWorstExtra spaceStableGood for
Bubble sortO(n)O(n²)O(n²)O(1)YesTeaching; detecting an already sorted array
Insertion sortO(n)O(n²)O(n²)O(1)YesSmall or nearly sorted arrays, online input
Selection sortO(n²)O(n²)O(n²)O(1)NoMinimizing swaps (at most n − 1)
Merge sortO(n log n)O(n log n)O(n log n)O(n)YesGuaranteed speed, linked lists, external sorting
Quick sortO(n log n)O(n log n)O(n²)O(log n)NoFast general-purpose in-memory sorting
Heap sortO(n log n)O(n log n)O(n log n)O(1)NoWorst-case guarantee without extra memory
Radix sort (LSD)O(d·(n+b))O(d·(n+b))O(d·(n+b))O(n+b)YesIntegers or fixed-length keys

n is the number of items, d the number of digits in the largest key and b the base (10 here). Any sort that only compares items needs at least about log₂(n!) ≈ n·log₂(n) − 1.44n comparisons in the worst case, which is why O(n log n) is the best a comparison sort can do.

Experiments worth trying

  • Nearly sorted data: run insertion sort and bubble sort, then quick sort. The simple algorithms finish in close to n steps while Lomuto quick sort slows to its worst case.
  • Few unique values: radix sort needs the same number of passes regardless of order, while quick sort with this partition scheme makes many redundant comparisons on duplicate keys.
  • Count the swaps: selection sort makes at most n − 1 swaps but always n(n − 1)/2 comparisons; bubble sort can make up to n(n − 1)/2 swaps.
  • Double the size: going from 50 to 100 items roughly quadruples the comparisons of O(n²) algorithms but only slightly more than doubles them for merge and heap sort.

Frequently asked questions

Which sorting algorithm is the fastest?

For general data, O(n log n) algorithms such as quick sort, merge sort and heap sort beat O(n²) ones like bubble, insertion and selection sort once arrays have more than a few dozen items. Quick sort is usually fastest in practice thanks to cache-friendly in-place partitioning, but its worst case is O(n²). Insertion sort wins on tiny or nearly sorted arrays, which is why library sorts such as Timsort and introsort switch to it for small pieces.

Why does quick sort get slow on sorted or reversed data here?

This visualizer uses the textbook Lomuto partition with the last element as the pivot. On data that is already sorted or reversed, that pivot is always the smallest or largest value, so each partition only removes one element and the run takes about n²/2 comparisons. Real libraries avoid this with random or median-of-three pivots.

What is a stable sort?

A stable sort keeps items with equal keys in their original relative order. Bubble, insertion, merge and radix sort are stable; selection, quick and heap sort are not. Stability matters when you sort by one field after another, such as sorting by name and then by department.

How can radix sort make zero comparisons?

Radix sort never compares two values. It distributes numbers into ten buckets by one digit at a time, starting from the ones place, using a stable counting pass. Its running time is O(d·(n + b)) for d digits and base b, so for fixed-width integers it can beat comparison sorts, whose lower bound is about n·log₂(n) comparisons.

What counts as a step?

One step is one elementary operation: comparing two items, swapping two items, writing a value into the array, or (for radix sort) reading a digit. A swap counts as two array writes. Steps are what the speed slider controls and what the race compares, so they reflect work done rather than wall-clock time on your computer.

What do the colors mean?

Amber bars are being compared or read, red bars are being swapped or written, purple marks the pivot or the current key or minimum, and dark green bars have reached their final sorted position. In merge sort the shaded band shows the part of the array being merged.

Are all the tools on FreeToolCabin tested for quality and accuracy?

Yes! Every tool on our site undergoes automated Q/A testing in real browser environments to ensure high precision, correct output, and zero errors. If you happen to spot a bug or have a suggestion, please contact us at [email protected] and our team will review it right away.

Related tools

Karnaugh Map SolverSolve 2–6 variable K-maps: click cells or enter minterms to get the minimal SOP or POS with groups.Sort NumbersPull numbers out of any text and sort them ascending or descending, with sum, average and median.Binary CalculatorAdd, subtract, multiply, divide, AND, OR, XOR and shift binary numbers with decimal values.Regex TesterTest and debug regular expressions live.Online Python CompilerRun Python 3 in your browser with input(), numpy, pandas, charts and share links.JSON EditorEdit JSON in a tree and as code side by side: add, rename, drag, change types, undo and download.Unzip FilesOpen and extract ZIP files online.RAR & 7z ExtractorOpen RAR, 7z and other archives online and extract files.File Info ViewerCheck file size, type, date and MD5/SHA hashes.SQLite ViewerOpen .db and .sqlite files in your browser, browse tables and run SQL queries.DOCX ViewerOpen and read Word .docx files in your browser, then print or save them as HTML.EPUB ReaderOpen and read EPUB e-books in your browser with pages, a table of contents and font controls.What Is My BrowserSee your browser, version, OS, engine, screen and which web features it supports.Font ViewerPreview TTF, OTF, WOFF and WOFF2 fonts with sample text, waterfall, glyphs and metadata.Markdown EditorWrite Markdown with a toolbar, live split preview, autosave and .md or HTML export.Regex Cheat Sheet75+ ready-to-use regex patterns for emails, URLs, IPs and dates, each with a live test box.JavaScript Keycode FinderPress any key to see its JavaScript key, code, keyCode, which, location and modifiers.QR Code ScannerScan QR codes with your camera or from an image and safely read the link or text.RAID CalculatorUsable capacity, efficiency and fault tolerance for RAID 0, 1, 5, 6, 10, 50 and 60 arrays.JSONPath TesterTest JSONPath expressions live: filters, slices, wildcards and recursive search, with matches highlighted.Mermaid Diagram EditorWrite Mermaid code and see flowcharts, sequence, Gantt and ER diagrams live. Export SVG or PNG.Country Codes ListSearch ISO 3166 alpha-2, alpha-3 and numeric country codes with calling codes and TLDs.CSS Selector TesterTest CSS selectors on your HTML: highlighted matches, match count and specificity.Git Cheat SheetSearchable Git command reference by task, with copy buttons and an undo/rename/fix wizard.HAR File ViewerOpen a .har file to see a waterfall timeline, headers, bodies, timings and size totals.jq PlaygroundRun jq filters on JSON in your browser with live output, flags and an example library.Markdown Cheat SheetInteractive Markdown syntax reference: edit every example and see the live rendered preview.Regex ExplainerPaste a regular expression and get a plain-English breakdown, railroad diagram and flag notes.XPath TesterTest XPath expressions on XML or HTML: highlighted matches, node paths, values and examples.EML File ViewerOpen .eml email files to read the message, headers and raw source and save attachments.Graphviz Online ViewerWrite Graphviz DOT code and render graphs live; switch layout engines, export SVG or PNG.JavaScript Online CompilerWrite and run JavaScript in your browser with a console, timing, error lines and share links.Jupyter Notebook ViewerOpen .ipynb files and read code, Markdown, math, tables, plots and errors without Python.LaTeX Table GeneratorEdit a table like a spreadsheet or paste from Excel and get LaTeX tabular or booktabs code.Log File ViewerOpen huge log files with level colors, regex and time filters, JSON pretty-print and tail -f.Logic Gate SimulatorBuild logic circuits with AND, OR, NOT, XOR gates and flip-flops; see live outputs and truth tables.MSG File ViewerOpen Outlook .msg emails in your browser: sender, recipients, body, headers and attachments.Online Code EditorVS Code-style editor in your browser: tabs, 50+ languages, find/replace, autosave.Lottie ViewerOpen Lottie JSON or .lottie files to play, pause, scrub frames, change speed and see details.Diff ViewerPaste a git diff or .patch file and view it side by side or inline, with file navigation.EditorConfig GeneratorBuild an .editorconfig with indent, charset, line endings and trim rules per file pattern.Folder Compare ToolCompare two folders by file list, size and SHA-256 hash, then open a text diff of changed files.Glob Pattern TesterTest glob patterns like **/*.js, {a,b} and !exclusions against a list of file paths.JMESPath TesterEvaluate JMESPath expressions against JSON live, the query language used by the AWS CLI.MongoDB Query TesterTest MongoDB find filters, projections and aggregation pipelines on sample JSON documents.Semantic Version CalculatorBump, compare, sort and test SemVer versions against npm ^, ~ and x ranges.XSLT TesterRun an XSLT 1.0 stylesheet on XML in your browser and see the output as HTML, XML or text.ASCII Diagram EditorDraw boxes, arrows and text on a character grid and copy plain-text diagrams for code and READMEs.DBF File ViewerOpen dBase .dbf files and shapefile tables, search and sort records, export CSV or XLSX.MBOX File ViewerOpen .mbox mail archives: list and search messages, read them, save attachments, export EML.MDB File ViewerOpen Access .mdb and .accdb databases in your browser: list tables, view rows, export CSV.Shapefile ViewerView zipped shapefiles on a map with the attribute table, then export to GeoJSON or CSV.Online Hex EditorOpen any file as hex and ASCII, edit bytes, search, inspect values and save the result.PHP Online CompilerRun PHP 8 code in your browser with output, HTML preview, error lines and share links.PlantUML EditorWrite PlantUML and see sequence, class, activity and more diagrams live. Export SVG or PNG.
See all 53 Code Playgrounds & Testers →