Skip to main content
Computer Science Sorting Algorithms

Sorting Algorithms

Visual comparison of sorting algorithms with real-time performance metrics

Actions
Array Size
50
Animation Speed
© 2013 - 2026 Cylian 🤖 Claude
Instructions Claude

Prompt utilisé pour régénérer cette page :

Page: Sorting Algorithms - Visual Comparison
Title: "Sorting Algorithms"
Description: "Visual comparison of sorting algorithms with real-time performance metrics"
Icon: sort
Tags: algorithm, sorting, performance, visualization
Category: computer-science
Front matter: js: default, scss: default

HTML structure in index.md:
  <section class="sorting-container container visual">
    <div class="sorting-grid" id="sorting-grid"></div>
  </section>
  <section class="sorting-stats section">
    <div id="sorting-stats"></div>
  </section>

Widget files:
  _controls.right.md (weight: 100, title: "Controls", _build: render: never, list: never):
    ##### Actions
    div.button-group.vertical:
      {{< button id="btn-run" color="green" label="Run All" >}}
      {{< button id="btn-reset" color="blue" label="Reset" >}}

  _options.right.md (weight: 200, title: "Options", _build: render: never, list: never):
    ##### Array Size
    div.slider-group: <input type="range" id="sorting-size" min="10" max="200" value="50" class="slider"> + <span id="size-label">50</span>
    ##### Animation Speed
    <input type="range" id="sorting-speed" min="1" max="100" value="50" class="slider">

Architecture (8 JS files):
  default.js — Main orchestrator (ES module):
    Imports: { bubbleSort } from ./_bubble.lib.js, { selectionSort } from ./_selection.lib.js, { insertionSort } from ./_insertion.lib.js, { mergeSort } from ./_merge.lib.js, { quickSort } from ./_quick.lib.js, { heapSort } from ./_heap.lib.js
    CONFIG: defaultSize=50, minSize=10, maxSize=200, defaultSpeed=50, barGap=1
    CONFIG.colors: bar=var(--color-blue), comparing=var(--color-yellow), swapping=var(--color-red), sorted=var(--color-green), pivot=var(--color-purple)
    ALGORITHMS map (6 entries): bubble/selection/insertion (O(n²)), merge/quick/heap (O(n log n)). Each has name, fn (imported function), complexity string
    State: gridEl, statsEl, arraySize=50, animationSpeed=50, isRunning, activeVisualizers[]

    SortVisualizer class:
      constructor(algoKey, container): Stores algo reference, creates DOM structure, gets canvas context
      init(): Creates innerHTML: .algo-header (name + complexity), canvas.algo-canvas, .algo-metrics (3 spans: Comparisons, Swaps, Time)
      resize(): Sets canvas.width = container width - 20px, canvas.height = 150, re-renders
      generateArray(size): Creates random array, resets metrics/highlights/isComplete
      setArray(arr): Copies array ([...arr]), resets metrics/highlights/isComplete
      run(speed): Async. Starts performance.now() timer. Creates visualize callback:
        - Clears highlights, sets new highlights from indices
        - 'compare' type increments comparisons, 'swap' increments swaps
        - Calls updateMetrics + render + sleep(max(1, 100-speed))
        - After sort: records time, sets isComplete=true, clears highlights
      updateMetrics(): Updates 3 <strong> elements with comparisons/swaps/time
      render(): Clears canvas, draws bars. barWidth = (canvasWidth - (n-1)*barGap) / n. barHeight = value * (height-10). Colors: isComplete → green, highlight 'compare' → yellow, 'swap' → red, 'pivot' → purple, 'sorted' → green, default → blue

    sleep(ms): Returns Promise wrapping setTimeout
    generateMasterArray(size): Creates random array of given size (values 0-1)
    initVisualizers(algoKeys): Clears grid, creates .algo-panel div + SortVisualizer for each key, calls resetArrays()
    resetArrays(): Generates master array, distributes copy to each visualizer via setArray([...arr])
    runAll(): Guards with isRunning flag, disables buttons, runs all visualizers in parallel (Promise.all), then updates stats
    updateStats(): Builds HTML <table class="stats-table"> with columns: Algorithm, Complexity, Comparisons, Swaps, Time
    updateButtons(): Disables btn-run and btn-reset during isRunning
    handleSizeChange(size): Clamps to min/max, sets arraySize, calls resetArrays()
    handleSpeedChange(speed): Updates animationSpeed variable

    init(): Gets gridEl (#sorting-grid), statsEl (#sorting-stats). Binds:
      btn-run click → runAll
      btn-reset click → resetArrays
      sorting-size input → handleSizeChange + update size-label text
      sorting-speed input → handleSpeedChange
      window resize → resize() on all visualizers
    Initializes with all 6 algorithms: ['bubble','selection','insertion','merge','quick','heap']
    Auto-init: readyState check + DOMContentLoaded

  _bubble.lib.js — Bubble Sort (named export: bubbleSort):
    O(n²) time, O(1) space. Nested loops comparing adjacent elements
    Optimization: early exit if no swaps in a pass (swapped flag)
    Visualize: 'compare' [j, j+1], 'swap' [j, j+1], 'sorted' [n-i-1] after each pass

  _selection.lib.js — Selection Sort (named export: selectionSort):
    O(n²) time, O(1) space. Finds minimum in unsorted portion
    Visualize: 'compare' [minIdx, j], 'swap' [i, minIdx], 'sorted' [i]

  _insertion.lib.js — Insertion Sort (named export: insertionSort):
    O(n²) time, O(1) space. Builds sorted array by inserting elements into correct position
    Uses key variable + shift loop (while j>=0 && arr[j]>key)
    Visualize: 'compare' [i], 'compare' [j, j+1], 'swap' [j, j+1], 'sorted' [j+1]

  _merge.lib.js — Merge Sort (named export: mergeSort):
    O(n log n) time, O(n) space. Recursive divide-and-conquer
    mergeSort → mergeSortHelper(arr, left, right) → merge(arr, left, mid, right)
    merge(): Creates leftArr/rightArr copies via slice, merges back in-place
    Visualize: 'compare' [left+i, mid+1+j], 'swap' [k] on each placement

  _quick.lib.js — Quick Sort (named export: quickSort):
    O(n log n) average / O(n²) worst time, O(log n) space. Uses last element as pivot
    quickSort → quickSortHelper(arr, low, high) → partition(arr, low, high)
    partition(): Lomuto scheme — pivot=arr[high], i tracks boundary
    Visualize: 'pivot' [high], 'compare' [j, high], 'swap' [i, j], 'sorted' [i+1]

  _heap.lib.js — Heap Sort (named export: heapSort):
    O(n log n) time, O(1) space. Builds max-heap then extracts max repeatedly
    heapSort → heapify(arr, n, i). Build phase: i from floor(n/2)-1 down to 0
    Extract phase: swap root with end, heapify reduced heap
    heapify(): Compares with left (2i+1) and right (2i+2) children, swaps if larger, recurses
    Visualize: 'compare' [largest, left/right], 'swap' [i, largest], 'sorted' [i] during extraction

  All algorithm functions share the same interface:
    async fn(array, visualize) where visualize is async callback(type, indices)
    type = 'compare'|'swap'|'pivot'|'sorted', indices = array of highlighted positions
    Algorithms modify array in-place
    Delay between steps: max(1, 100 - speed) ms

default.scss:
  .sorting-container: padding var(--layout-spacing)
  .sorting-grid: display grid, grid-template-columns repeat(2, 1fr), gap var(--layout-spacing) — 2 columns x 3 rows layout
  .algo-panel: background var(--background-color-surface), border-radius var(--border-radius), padding 1rem, border 1px solid var(--border-color)
  .algo-header: flex space-between, margin-bottom 0.5rem
  .algo-name: font-weight bold, var(--text-color-primary)
  .algo-complexity: monospace, 0.8rem, var(--text-color-secondary), background var(--background-color), padding 0.2rem 0.5rem, border-radius 3px
  .algo-canvas: width 100%, height 150px, background var(--background-color), border-radius var(--border-radius), margin-bottom 0.5rem
  .algo-metrics: flex space-between, font-size 0.75rem, color var(--text-color-secondary). strong: var(--text-color-primary)
  .slider-group: flex, gap 0.5rem. .slider flex:1. span min-width 2rem, right-aligned, monospace
  .sorting-stats: margin-top var(--layout-spacing)
    .stats-table: width 100%, border-collapse. th/td padding 0.5rem, border-bottom. th background var(--background-color-surface). code with background + padding + 3px radius

Important implementation notes:
  - Master array ensures identical input for fair comparison between algorithms
  - Each visualizer gets a COPY ([...arr]) not a reference
  - All 6 algorithms run in parallel via Promise.all
  - Canvas cleared fully each render (not trail-based)
  - barGap = 1px between bars
  - Bar height = value * (canvasHeight - 10), values are 0-1 floats from Math.random()
  - isRunning flag prevents concurrent runs, disables buttons during sort
  - After completion: all bars turn green (isComplete=true), stats table updated
  - Window resize triggers resize() on all visualizers (re-measures container width)
  - No devicePixelRatio scaling on canvases

Page entièrement générée et maintenue par IA, sans intervention humaine.