惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
T
Threat Research - Cisco Blogs
美团技术团队
IT之家
IT之家
Apple Machine Learning Research
Apple Machine Learning Research
Microsoft Azure Blog
Microsoft Azure Blog
小众软件
小众软件
Engineering at Meta
Engineering at Meta
U
Unit 42
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
MongoDB | Blog
MongoDB | Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The Cloudflare Blog
Last Week in AI
Last Week in AI
M
MIT News - Artificial intelligence
G
Google Developers Blog
博客园 - 三生石上(FineUI控件)
Vercel News
Vercel News
The Register - Security
The Register - Security
Cyberwarzone
Cyberwarzone
F
Fortinet All Blogs
L
LINUX DO - 热门话题
C
Check Point Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
Know Your Adversary
Know Your Adversary
S
Security Affairs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Webroot Blog
Webroot Blog
V2EX - 技术
V2EX - 技术
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Martin Fowler
Martin Fowler
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
I
InfoQ
Cisco Talos Blog
Cisco Talos Blog
博客园 - 司徒正美
aimingoo的专栏
aimingoo的专栏
T
The Exploit Database - CXSecurity.com
博客园 - 【当耐特】
C
CERT Recently Published Vulnerability Notes
酷 壳 – CoolShell
酷 壳 – CoolShell
云风的 BLOG
云风的 BLOG
L
Lohrmann on Cybersecurity
T
Threatpost
腾讯CDC
Security Latest
Security Latest
K
Kaspersky official blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Stack Overflow Blog
Stack Overflow Blog
Help Net Security
Help Net Security
Forbes - Security
Forbes - Security

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Visualizing 4 Sorting Algorithms with JavaScript Generators — O(n ) vs O(n log n) in Real Time
SEN LLC · 2026-05-22 · via DEV Community

Sorting visualizers are a genre. This one is different in one way that matters: the algorithm code has zero knowledge of the DOM. Bubble, Insertion, Merge, and Quick Sort are plain generator functions that yield at every comparison and swap. The animation driver calls .next() on a timer and updates bars. Changing "algorithm" means swapping the generator. Nothing else changes.

Sort Visualizer: dark-background bar chart with 50 bars in shades of blue, yellow (comparing), red (swapping), and green (sorted). Bubble Sort tab is active. Controls show Size = 50, Speed slider, Shuffle and Start buttons. Stats: Comparisons: 312, Swaps: 147.

🌐 Demo: https://sen.ltd/portfolio/sort-visualizer/
📦 GitHub: https://github.com/sen-ltd/sort-visualizer

Why generators?

The usual approach: mix the algorithm and the DOM in a single function, using async/await + sleep() to pause.

// the common pattern — tightly coupled
async function bubbleSort(bars) {
  for (let i = 0; i < bars.length - 1; i++) {
    for (let j = 0; j < bars.length - 1 - i; j++) {
      bars[j].style.background = "yellow";     // DOM inside sort logic
      bars[j + 1].style.background = "yellow";
      await sleep(delay);
      if (height(bars[j]) > height(bars[j + 1])) {
        swap(bars[j], bars[j + 1]);
        await sleep(delay);
      }
      bars[j].style.background = "";
      bars[j + 1].style.background = "";
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

Problems:

  • Can't test the sort logic without a DOM.
  • Changing animation speed or stopping mid-sort requires ugly cancelled flags.
  • Adding a new algorithm means copy-pasting the sleep + color update infrastructure.

The generator approach separates concerns cleanly:

// sorters.js — no DOM, no timers
export function* bubbleSort(arr, colors, stats) {
  const n = arr.length;
  for (let i = 0; i < n - 1; i++) {
    for (let j = 0; j < n - 1 - i; j++) {
      stats.comparisons++;
      colors[j] = colors[j + 1] = "comparing";
      yield;                                    // pause here
      if (arr[j] > arr[j + 1]) {
        stats.swaps++;
        colors[j] = colors[j + 1] = "swapping";
        yield;                                  // pause here
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
      }
      colors[j] = colors[j + 1] = "default";
    }
    colors[n - 1 - i] = "sorted";
  }
  colors[0] = "sorted";
}

Enter fullscreen mode Exit fullscreen mode

The animation driver in index.html:

function startAnimation() {
  const gen = ALGO_MAP[currentAlgo](array, colors, stats);

  function step() {
    const { done } = gen.next();   // advance one yield
    render();                       // paint whatever state we're in
    if (!done) animId = setTimeout(step, delay());
    else finishAnimation();
  }

  animId = setTimeout(step, delay());
}

Enter fullscreen mode Exit fullscreen mode

delay() reads the speed slider at call time — so the user can change speed mid-sort and it takes effect immediately on the next step.

Stopping is trivial: clearTimeout(animId). No cancelled flag, no promises to abort.

What each algorithm yields

Here's what the color transitions look like per algorithm:

Bubble Sort

Classic two-pointer walk. The n - 1 - i position is guaranteed sorted after pass i.

for each pass i:
  for j from 0 to n-2-i:
    mark [j, j+1] as comparing → yield
    if out of order:
      mark [j, j+1] as swapping → yield → swap
    reset [j, j+1] to default
  mark [n-1-i] as sorted

Enter fullscreen mode Exit fullscreen mode

O(n²) comparisons. O(n²) swaps worst case. Already-sorted input: 0 swaps, but still O(n²) comparisons.

Insertion Sort

Pick each element, shift right to find its place.

export function* insertionSort(arr, colors, stats) {
  const n = arr.length;
  for (let i = 1; i < n; i++) {
    const key = arr[i];
    colors[i] = "comparing";
    yield;
    let j = i - 1;
    while (j >= 0) {
      stats.comparisons++;
      colors[j] = "comparing";
      yield;
      if (arr[j] > key) {
        stats.swaps++;
        colors[j + 1] = "swapping";
        arr[j + 1] = arr[j];      // shift right
        yield;
        colors[j + 1] = "default";
        colors[j] = "default";
        j--;
      } else {
        colors[j] = "sorted";
        break;
      }
    }
    arr[j + 1] = key;
    for (let k = 0; k <= i; k++) colors[k] = "sorted";  // ← important
    yield;
  }
}

Enter fullscreen mode Exit fullscreen mode

Color tracking gotcha: during the shift phase, multiple positions change from their original values. If you mark individual positions "sorted" during the shift (rather than after placing the key), you get positions that are colored "sorted" but don't yet hold their final value. The fix: re-mark the full sorted prefix [0..i] after each outer iteration.

O(n²) worst case, but O(n) on nearly-sorted input — good for "almost sorted" real-world data.

Merge Sort

Divide-and-conquer with a temp buffer.

function* _merge(arr, colors, stats, l, m, r) {
  const left  = arr.slice(l, m + 1);  // temp copy
  const right = arr.slice(m + 1, r + 1);
  let i = 0, j = 0, k = l;

  while (i < left.length && j < right.length) {
    stats.comparisons++;
    colors[k] = "comparing";
    yield;
    if (left[i] <= right[j]) { arr[k] = left[i++]; }
    else { stats.swaps++; arr[k] = right[j++]; }
    colors[k] = "swapping";
    yield;
    colors[k++] = "default";
  }
  // drain remainder ...
}

Enter fullscreen mode Exit fullscreen mode

Delegating recursion through generators requires yield*:

function* _mergeHelper(arr, colors, stats, l, r) {
  if (l >= r) return;
  const m = (l + r) >> 1;
  yield* _mergeHelper(arr, colors, stats, l, m);      // delegate
  yield* _mergeHelper(arr, colors, stats, m + 1, r);  // delegate
  yield* _merge(arr, colors, stats, l, m, r);         // delegate
}

Enter fullscreen mode Exit fullscreen mode

yield* propagates each yield up the call chain — the outer animation driver receives them all as if they came from one flat generator.

O(n log n) always. Extra O(n) space for the temp arrays.

Quick Sort

Lomuto partition scheme: pick the last element as pivot.

function* _partition(arr, colors, stats, low, high) {
  const pivot = arr[high];
  colors[high] = "pivot";   // orange color signals the pivot
  let i = low - 1;

  for (let j = low; j < high; j++) {
    stats.comparisons++;
    colors[j] = "comparing";
    yield;
    if (arr[j] <= pivot) {
      i++;
      if (i !== j) {
        stats.swaps++;
        colors[i] = colors[j] = "swapping";
        [arr[i], arr[j]] = [arr[j], arr[i]];
        yield;
        colors[i] = "default";
      }
    }
    colors[j] = "default";
  }
  // place pivot at i+1
  // ...
  return i + 1;
}

Enter fullscreen mode Exit fullscreen mode

The pivot color (orange) makes it visually obvious which element is partitioning the array.

O(n log n) average, O(n²) worst case (already-sorted or all-equal input with Lomuto). Each iteration n - 1 - i elements are guaranteed sorted, so we mark colors[pivotPos] = "sorted" immediately after partition.

Testing without a DOM

Because generators are pure functions over plain arrays, the test suite is straightforward:

import { bubbleSort, insertionSort, mergeSort, quickSort, runSort } from "../sorters.js";

function run(algo, input) {
  const arr    = [...input];
  const colors = new Array(arr.length).fill("default");
  const stats  = { comparisons: 0, swaps: 0 };
  runSort(algo(arr, colors, stats));
  return { arr, colors, stats };
}

test("bubbleSort sorts a random array", () => {
  const { arr } = run(bubbleSort, [5, 3, 8, 1, 9, 2, 7, 4, 6]);
  assert.deepEqual(arr, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
});

test("all bars end as sorted", () => {
  for (const algo of [bubbleSort, insertionSort, mergeSort, quickSort]) {
    const { colors } = run(algo, [3, 1, 4, 1, 5, 9, 2, 6]);
    assert.ok(colors.every(c => c === "sorted"));
  }
});

Enter fullscreen mode Exit fullscreen mode

runSort just drains the generator:

export function runSort(gen) {
  while (!gen.next().done) {}
}

Enter fullscreen mode Exit fullscreen mode

46 tests, zero mocking, no jsdom.

What you can see in the visualizer

At speed 1 (slowest), watch:

  • Bubble: the sorted green grows from the right one element per pass.
  • Insertion: the sorted green grows from the left as each key finds its place.
  • Merge: wide orange bands appear at the merge boundaries; yellow comparisons happen within small segments.
  • Quick: an orange pivot jumps around; after partition, its final position lights up green and never moves again.

At speed 5 (fastest), Bubble on 120 elements becomes a blur while Merge and Quick finish in a fraction of the time — a direct visual comparison of O(n²) vs O(n log n).

TL;DR

  • Generator + yield separates algorithm logic from animation — no DOM in the sort code, no sort code in the animation driver.
  • yield* delegates yields through recursive calls, keeping the driver simple.
  • Speed changes take effect immediately because delay() reads the slider on each setTimeout callback.
  • Stop is clearTimeout — no cancellation flags needed.
  • Color tracking in insertion sort requires re-marking the full sorted prefix after each placement, not individual positions during the shift.
  • Tests run in Node without any browser or mock DOM.

Source: https://github.com/sen-ltd/sort-visualizer — MIT, ~200 lines of JS (sorters) + ~150 lines of UI, 46 unit tests, zero dependencies, no build step.


🛠 Built by SEN LLC as part of an ongoing series of small, focused developer tools. Browse the full portfolio for more.