← back to home

Sorting Visualizer

20212 viewsView on GitHub
AlgorithmsVisualization

An interactive visualization of common sorting algorithms built with React

A React app that visualizes sorting algorithms with animated bars. Watch Bubble Sort, Selection Sort, Insertion Sort, Quick Sort, and Heap Sort run step-by-step—color-coded to show comparisons, swaps, and sorted elements as they happen.

What's Inside

Sorting Algorithms

Five algorithms, each running as an async function so the animation can pause between steps:

Visualization

Each array element is a vertical bar—height = value. Bars use CSS transforms for positioning, so swaps animate smoothly (250ms transition). The swap logic creates a temp DOM node and uses replaceWith to exchange elements while transforms handle the visual movement.

Colors indicate state: purple for unsorted, dark purple for currently comparing, green for sorted. Each algorithm also has its own accent colors for special elements (pivot, current min, heap root, etc.).

Controls

Everything's keyboard-driven. The shortcuts work even when the drawer is open, so you can swap algorithms while reading the code.

The drawer slides out to show syntax-highlighted source for the selected algorithm (using react-syntax-highlighter with a VS Code theme), plus a color legend and shortcut reference.

Quick Start

git clone https://github.com/rahulgpt/sorting-visualizer.git
cd sorting-visualizer
npm install
npm start

Opens at http://localhost:3000.

How It Works

Animation

Each algorithm is async, awaiting promises for timing delays. getValue reads the bar's numeric value from its span, setColor updates backgrounds. After swaps, the algorithm re-queries child nodes since DOM order changed.

Generate Array → Trigger Algorithm → Async Loop with Delays →
Compare & Color → Swap (Transform Animation) → Update DOM →
Mark Sorted → Callback

Components

The main Visualizer is a class component managing array state, algorithm flags, a lock to prevent concurrent sorts, and drawer state. Keyboard listeners attach in componentDidMount, algorithms fire from componentDidUpdate when flags change.

Styled-components handle everything visual—gradient nav, bar wrappers, screen-size warning overlay. Container positions children absolutely; each BarWrapper translates horizontally by index.

Config

Colors live in app_config.js. Shared colors (base purple, comparison purple, sorted green) apply across algorithms, with per-algorithm extras for pivots, minimums, etc.

Keyboard Shortcuts

Limitations

Needs a minimum of 876×624px (shows a warning on smaller screens). One sort at a time—stop the current one before starting another. Array size is fixed at 20 elements, and animation speed is hardcoded.

1kudos