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

推荐订阅源

Google DeepMind News
Google DeepMind News
S
Security Affairs
阮一峰的网络日志
阮一峰的网络日志
L
LangChain Blog
Microsoft Azure Blog
Microsoft Azure Blog
雷峰网
雷峰网
Recent Announcements
Recent Announcements
WordPress大学
WordPress大学
The GitHub Blog
The GitHub Blog
博客园_首页
The Cloudflare Blog
M
MIT News - Artificial intelligence
博客园 - 【当耐特】
MyScale Blog
MyScale Blog
S
SegmentFault 最新的问题
P
Proofpoint News Feed
Y
Y Combinator Blog
Jina AI
Jina AI
博客园 - 聂微东
A
About on SuperTechFans
Blog — PlanetScale
Blog — PlanetScale
博客园 - 司徒正美
G
Google Developers Blog
云风的 BLOG
云风的 BLOG
F
Full Disclosure
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Microsoft Security Blog
Microsoft Security Blog
爱范儿
爱范儿
T
Tailwind CSS Blog
J
Java Code Geeks
Vercel News
Vercel News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Stack Overflow Blog
Stack Overflow Blog
罗磊的独立博客
小众软件
小众软件
酷 壳 – CoolShell
酷 壳 – CoolShell
T
The Blog of Author Tim Ferriss
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
博客园 - 三生石上(FineUI控件)
W
WeLiveSecurity
PCI Perspectives
PCI Perspectives
Attack and Defense Labs
Attack and Defense Labs
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
宝玉的分享
宝玉的分享
IT之家
IT之家
Hacker News: Ask HN
Hacker News: Ask HN
The Register - Security
The Register - Security
T
The Exploit Database - CXSecurity.com
T
Threat Research - Cisco Blogs

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
Integer Sorting via Value-Space Partitioning
Haris Abdull · 2026-05-09 · via DEV Community

Generalizing Dijkstra's Dutch National Flag Algorithm

Dijkstra's Dutch National Flag (DNF) algorithm is one of those deceptively simple ideas that becomes more interesting the deeper you look into it.

At first glance, it solves a very narrow problem: sorting an array containing only 0, 1, and 2 in a single linear pass. Elegant, clever, and usually treated as a specialized trick.

But hidden inside DNF is a much more general idea.

The algorithm works because it understands the structure of the value space. It knows exactly which values belong on the left, which belong on the right, and which belong in the middle. Once you stop thinking of DNF as "sorting three values" and start thinking of it as "partitioning a known value space," the natural question becomes:

Can this idea be generalized to arbitrary integer arrays?

This article explores two algorithms built from that idea:

  • SweepSort — a direct generalization of DNF
  • SweepSort2 — a recursive value-space partitioning algorithm with linear worst-case behavior for fixed-width integers

Revisiting the Dutch National Flag Algorithm

The original DNF algorithm maintains three regions:

  • low region (0)
  • middle region (1)
  • high region (2)

and sweeps through the array once, routing elements into their correct regions using swaps.

The critical insight is not the swaps themselves.

The real insight is this:

DNF succeeds because the value space is completely known in advance.

The algorithm always knows:

  • the smallest possible value,
  • the largest possible value,
  • and the bounded middle region.

That structure is what makes single-pass partitioning possible.

Now imagine replacing the hardcoded values 0, 1, and 2 with dynamically discovered boundaries.

That leads directly to the first algorithm.


SweepSort: A Direct Generalization of DNF

SweepSort extends DNF to arbitrary integer arrays.

Instead of partitioning around fixed values, it repeatedly:

  1. finds the current minimum and maximum,
  2. sweeps them to the ends,
  3. and discovers the next minimum and maximum during the same pass.
void SweepSort(int* array, size_t n) {

    int max = INT_MIN, min = INT_MAX;

    for (size_t i = 0; i < n; i++) {

        max = Max(max, array[i]);
        min = Min(min, array[i]);
    }

    size_t low = 0, mid = 0, high = n;

    while (mid < high) {

        int new_min = INT_MAX;
        int new_max = INT_MIN;

        while (mid < high) {

            if (array[mid] == max) {

                --high;
                Swap(array + mid, array + high);
            }
            else if (array[mid] == min) {

                Swap(array + mid, array + low);
                ++low, ++mid;
            }
            else {

                new_min = Min(new_min, array[mid]);
                new_max = Max(new_max, array[mid]);

                ++mid;
            }
        }

        min = new_min;
        max = new_max;

        mid = low;
    }
}

Enter fullscreen mode Exit fullscreen mode


How SweepSort Works

Each sweep partitions the current unsorted region into three parts:

  • elements equal to min
  • elements strictly between min and max
  • elements equal to max

The process mirrors classic DNF almost exactly.

During each pass:

  • min values are swapped left,
  • max values are swapped right,
  • everything else remains in the middle.

At the same time, the algorithm computes the next new_min and new_max from the remaining middle region for free during the partition pass itself.

That detail is crucial.

Without it, each recursion level would require an additional scan, dramatically worsening performance.

Core Invariant

After every sweep:

  • [0, low) contains finalized minimum values,
  • [high, n) contains finalized maximum values,
  • [low, high) contains only values strictly between the next minimum and maximum.

The middle region shrinks until no unsorted values remain.


Complexity Analysis

Each pass removes at least two distinct values from the unsorted region:

  • the current minimum,
  • and the current maximum.

If the array contains k distinct values: O(k * n)

Best Case

If the number of distinct values is small (i.e. the original DNF case): O(n)

Worst Case

If all values are unique: O(n^2)

which places SweepSort in quadratic territory for adversarial inputs.

SweepSort is therefore more interesting conceptually than practically — it exposes the structure hidden inside DNF, but does not fully solve the scalability problem.

That leads to the second algorithm.


SweepSort2: Recursive Value-Space Partitioning

SweepSort2 changes perspective entirely.

Instead of repeatedly removing extrema, it recursively partitions the value space itself.

static void SweepSort2Core(int* array, size_t n, int min, int max) {

    if (min >= max) return;

    size_t low = 0, high = 0;

    int high_min = INT_MAX;
    int high_max = INT_MIN;

    int low_min = INT_MAX;
    int low_max = INT_MIN;

    int pivot = (max >= 0 && min < 0) ? -1 : min + (max - min) / 2;

    while (high < n) {

        if (array[high] > pivot) {

            high_min = Min(high_min, array[high]);
            high_max = Max(high_max, array[high]);
        }
        else {

            low_min = Min(low_min, array[high]);
            low_max = Max(low_max, array[high]);

            Swap(array + low, array + high);

            ++low;
        }

        ++high;
    }

    SweepSort2Core(array + low, n - low, high_min, high_max);
    SweepSort2Core(array, low, low_min, low_max);
}

void SweepSort2(int* array, size_t n) {
    SweepSort2Core(array, n, INT_MIN, INT_MAX);
}

Enter fullscreen mode Exit fullscreen mode


How SweepSort2 Works

Each recursive call partitions the array into two regions:

  • low region: values <= pivot
  • high region: values > pivot

This resembles quicksort superficially, but the recursion is driven by the value range, not the data distribution. The algorithm also computes the minimum and the maximum of the high and the low region during the partition pass itself.

No additional scans are required.


The Overflow Problem

This is the subtlest part of the algorithm.

The natural midpoint formula:

(min + max) / 2

Enter fullscreen mode Exit fullscreen mode

can overflow when min + max exceeds the representable integer range.

The standard fix is usually written as:

min + (max - min) / 2

Enter fullscreen mode Exit fullscreen mode

but that still fails when the range crosses zero.

For example:

min = INT_MIN
max = INT_MAX

Enter fullscreen mode Exit fullscreen mode

Here:

max - min

Enter fullscreen mode Exit fullscreen mode

itself overflows.

The problem is structural rather than arithmetic.

As long as recursion ranges are allowed to straddle zero, subtraction overflow remains possible.

The solution is to eliminate cross-zero ranges entirely:

int pivot = (max >= 0 && min < 0) ? -1 : min + (max - min) / 2;

Enter fullscreen mode Exit fullscreen mode

When the range straddles zero, the pivot becomes -1, partitioning the value space into:

  • negative integers,
  • and non-negative integers.

After this split:

  • negative-only ranges cannot overflow subtraction,
  • non-negative-only ranges cannot overflow subtraction.

The overflow hazard disappears permanently after the first cross-zero partition.

This is important because the fix is not merely arithmetic — it restructures the recursion tree itself.


Complexity Analysis

The recursion depth is bounded by how many times the value range can be halved.

For a value range of width R: O(n * log2(R))

For fixed-width 32-bit integers: log2(R) <= 32

giving: O(32 * n)

which simplifies to linear time under the fixed-word-size model.

Unlike comparison sorts, the recursion depth depends on the value-space width, not the number of elements.

This is the central idea behind SweepSort2.


Relationship to Radix Sorting

SweepSort2 is closely related to MSD binary radix sort.

Both algorithms:

  • recursively partition integers,
  • achieve bounded recursion depth,
  • and avoid comparison-sort lower bounds.

The key difference is that radix sort partitions explicit bits, while SweepSort2 partitions adaptive numeric intervals.

This makes SweepSort2 conceptually closer to recursive geometric partitioning of the integer space.


Comparison Summary

Property SweepSort SweepSort2
Core idea Repeated extrema sweeping Recursive value-space partitioning
Best case O(n) O(n)
Worst case O(n^2) O(n * log2(R))
32-bit integer worst case O(n^2) O(32 * n)
Recursion depth O(k) distinct values O(log2(R))
Stable No No
Extra memory O(1) recursion stack
Closest analog Generalized DNF MSD radix / American Flag Sort

Final Thoughts

SweepSort is primarily interesting because it exposes the hidden abstraction inside the Dutch National Flag algorithm.

SweepSort2 is where that abstraction becomes genuinely powerful.

The key realization is this:

Once recursion depth is bounded by value-space width rather than element count, linear worst-case behavior becomes possible for fixed-width integer data.

DNF turns out not to be a special-case trick for three values.

It is a concrete instance of a broader idea:

sorting by recursively partitioning value space itself.

That perspective was the real discovery behind these algorithms.