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

推荐订阅源

Google DeepMind News
Google DeepMind News
Attack and Defense Labs
Attack and Defense Labs
GbyAI
GbyAI
月光博客
月光博客
Recent Announcements
Recent Announcements
云风的 BLOG
云风的 BLOG
F
Full Disclosure
宝玉的分享
宝玉的分享
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
爱范儿
爱范儿
博客园 - Franky
V
V2EX
Recorded Future
Recorded Future
WordPress大学
WordPress大学
小众软件
小众软件
Webroot Blog
Webroot Blog
雷峰网
雷峰网
Vercel News
Vercel News
N
News and Events Feed by Topic
PCI Perspectives
PCI Perspectives
Cyberwarzone
Cyberwarzone
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
W
WeLiveSecurity
S
Schneier on Security
博客园 - 三生石上(FineUI控件)
K
Kaspersky official blog
F
Fortinet All Blogs
Security Archives - TechRepublic
Security Archives - TechRepublic
Spread Privacy
Spread Privacy
博客园 - 叶小钗
罗磊的独立博客
D
Docker
Forbes - Security
Forbes - Security
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
The Register - Security
The Register - Security
A
About on SuperTechFans
B
Blog RSS Feed
I
InfoQ
T
Tailwind CSS Blog
G
Google Developers Blog
H
Help Net Security
V
Vulnerabilities – Threatpost
AWS News Blog
AWS News Blog
N
News and Events Feed by Topic
M
MIT News - Artificial intelligence
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
P
Proofpoint News Feed
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
MyScale Blog
MyScale Blog
Latest news
Latest news

Hacker News: Show HN

PurrrrrFocus: Pomodoro Timer App - App Store Workflow Engine — Multi-Step Orchestration for Bun RapidPhoto: Pro Photo Editor App - App Store GitHub - DheerG/swarms: Achieve extraordinary results with claude code across a variety of tasks SPICE simulation → oscilloscope → verification with Claude Code — Lucas Gerads Show HN: VCoding – A 5 MB native Windows IDE with no dynamic dependencies Show HN: LLMs don't hallucinate because they're bad at math, it's the format GitHub - Agent-FM/agentfm-core: AgentFM is a peer-to-peer network that turns everyday computers into a decentralized AI supercomputer. AgentFM lets you run massive AI workloads directly across a global mesh of idle CPUs and GPUs. Show HN: Tracking Top US Science Olympiad Alumni over Last 25 Years GitHub - Potarix/agent-hub: One place to talk to all your agents Show HN: Runtime security for AI agents(injection,tool abuse, data exfiltration) GitHub - dubeyKartikay/lazyspotify: Terminal Spotify client for macOS and Linux GitHub - the-banana-tool/king-louie: Easy to use GUI Personal AI Assistant. Win/Linux/Mac. Show HN I made my vacation rental bookable by AI agents–no Airbnb, 0% commission GitHub - basteez/jsf-autoreload: maven plugin to enable hot reload on jsf projects uvm32/hosts/host-gdbstub at main · ringtailsoftware/uvm32 GitHub - labsai/EDDI: Config-driven engine that turns JSON into production-grade AI agents. Multi-agent orchestration, 12+ LLM providers, MCP/A2A protocols, RAG, persistent memory, and enterprise compliance (EU AI Act, GDPR, HIPAA). Built on Quarkus. GitHub - glitchnsec/fortyone-oss: AI Executive Assistant Platform Quickstart | Alien GitHub - muxshed/shed: One stream in, or many. Every destination, simultaneously. No cloud middleman, no per-channel fees, no limits. GitHub - ocrbase-hq/ocrbase: 📄 PDF/IMG ->.MD/JSON Document OCR API for PaddleOCR and GLMOCR. Self-hostable. GitHub - impactjo/home-memory: MCP server that lets your AI assistant remember everything about your home. GitHub - Sets88/dbcls: DbCls is a powerful terminal database client that supports various databases GitHub - neptun2000/heor-agent-mcp GitHub - SeanFDZ/macmind: Single-layer transformer in HyperTalk for the classic Macintosh RollQuation: Math Puzzles - Apps on Google Play GitHub - dropbox/witchcraft Show HN: Agent-cache – Multi-tier LLM/tool/session caching for Valkey and Redis GitHub - opentalon/opentalon: OpenTalon is an open-source platform built from the ground up in Go as a robust alternative to OpenClaw LinkedIn™ 职位抓取工具 - Chrome 应用商店 GitHub - EdoardoBambini/Agent-Armor-Iaga: AI agents are getting tool access — shell, file system, databases, APIs, secrets. But **nobody is governing what they actually do with it**. Frameworks like LangChain, CrewAI, AutoGen, and Claude Code give agents the power to execute. Agent Armor gives you the power to control, audit, and approve every single action before it happens. HN Vibes — Week 15, Apr 7–13 2026 GitHub - chojs23/ec: Easy terminal-native 3-way git mergetool vim-like workflow GitHub - SethPyle376/hiraeth: Local AWS emulator focused on fast integration testing, with SQS support, SQLite-backed state, and a debug-friendly web UI. GitHub - JakOb-dotcom/cloud-sandbox-security-analysis: Technical analysis and Proof of Concept (PoC) regarding environment variable exfiltration in containerized cloud sandboxes via side-channel data leaks. Springboards - Flint Alpha Show HN: A simpler coding agent harness GitHub - audiodude/sudomake-friends GitHub - 256thFission/mini-mythos: OSS clone of Anthropic’s Mythos harness to locate C/C++ memory vulnerabilities Show HN: OpenParallax: OS-level privilege separation for AI agent execution Hacker News Sorted - Chrome 应用商店 Show HN: How to Install Docker on Ubuntu 24.04 LTS: Complete 2026 Guide GitHub - himanshudongre/smriti GitHub - sverrirsig/claude-control: macOS desktop dashboard for monitoring and managing multiple Claude Code sessions GitHub - ory/dockertest: Write better integration tests! Dockertest helps you boot up ephermal docker images for your Go tests with minimal work. Chiral - Chrome 应用商店 Show HN: Two Claudes collaborating through shared memory on a $100 mini-PC GitHub - pmichaillat/latex-cv: Minimalist LaTeX template for academic CVs GitHub - oguzbilgic/posse: A web UI for Anthropic Managed Agents. GitHub - sshiraz/depsly: Dependency risk analysis tool for npm packages ABI Add safari/agent-harness — Safari browser automation via safari-mcp by achiya-automation · Pull Request #212 · HKUDS/CLI-Anything GitHub - Halfblood-Prince/trustcheck: Verify PyPI package attestations and improve Python supply-chain security GitHub - oguzbilgic/kern-ai: Agents that do the work and show it. GitHub - bruits/satteri: High-performance Markdown and MDX processing for the JavaScript ecosystem GitHub - tylergibbs1/feedstock: High-performance web crawler and scraper for TypeScript, powered by Bun and Playwright GitHub - Grimm67123/grimmbot: The self-improving sandboxed and open-source AI agent. With persistent memory and scheduling. GitHub - whitevanillaskies/whitebloom: Local whiteboard that blooms. GitHub - hwdsl2/docker-whisper: Docker image for a self-hosted Whisper speech-to-text server with speaker diarization and OpenAI-compatible transcription and translation APIs. Powered by faster-whisper. Supports all Whisper models, NVIDIA GPU (CUDA) acceleration, JSON/SRT/VTT output, SSE streaming, offline mode, and multi-arch (amd64, arm64). GitHub - yisding/reviewwiggum GitHub - MarwanAlsoltany/serrors: Structured errors for Go: sentinel hierarchies, typed data, custom formatting, and slog integration. GitHub - soatok/age-php GitHub - Luthiraa/markitme GitHub - stagas/rtdiff: realtime git diff gui and AI-assisted commits GitHub - tombedor/excalicharts GitHub - wh1le/excalidraw-edit: Open and edit .excalidraw files from the terminal. Offline, auto-saves to disk. MalExt Sentry - Malicious Extension Scanner - Chrome 应用商店 GitHub - syi0808/asciianimesvg: Generate animated ASCII art SVGs from text. CLI, Rust library, WASM, and web editor. GitHub - zaina-ml/ml_forge: A visual-based graph node editor for training computer vision models. GitHub - anakin87/llm-rl-environments-lil-course: 🌱 A little course on Reinforcement Learning Environments for evaluating and training Language Models GitHub - takaakit/superpowers-uml: Superpowers-UML modifies Superpowers to ensure a software development workflow in which AI agents design through UML modeling. AdriByte Studio - Sviluppo Web e Soluzioni Digitali GitHub - chouligi/angel-copilot: Your personalized Angel Investment Advisor Show HN: MoodSense AI (ML and FastAPI and Gradio, Deployed on Hugging Face) Moodsense Ai - a Hugging Face Space by aman179102 GitHub - agenteractai/lodmem: Level Of Detail Context Management for Agents GitHub - ostefani/subnetlens: A fast, concurrent network scanner with a TUI and plain-text CLI, built in Go. It discovers live hosts on your network, scans their open ports, resolves hostnames, and fingerprints operating systems—delivered. Cyber Pulse: Agentic Intel - Apps on Google Play Whisper API: Self-Hostable Speech to Text Transcription The Agent-Web Protocol Stack: A Research Thesis GitHub - msmarkgu/RelayFreeLLM: A restful API designed to route user prompts to various AI model providers. Show HN: Provepy – A Python decorator that proves your code using Lean and LLMs Show HN: Pardonned.com – A searchable database of US Pardons GitHub - patrickdappollonio/dux: Dux is a terminal UI that lets you run multiple AI coding agents side by side, each in its own git worktree, with full companion terminals, macros, commit generation, and a command palette that knows more tricks than you do. kMC Crystal Simulator Show HN: HyperFlow – A self-improving agent framework built on LangGraph GitHub - stef41/vibescore: 🎵 Grade your vibe-coded project. One command, instant letter grade across security, quality, dependencies, and testing. GitHub - stef41/lmscan: 🔍 Detect AI-generated text and fingerprint which LLM wrote it. Open-source GPTZero alternative. Zero dependencies, works offline. imgur.com GitHub - visionscaper/collabmem: Enabling long-term collaboration with Agentic AI - building up episodic and world model memory over time with in-context awareness 在 Steam 上购买 FriedrichAI: Offline AI 立省 10% GitHub - atripati/ark: AI Runtime Kernel — a context operating system for AI agents. Eliminates tool bloat, loads only what’s needed, and gives LLMs their reasoning space back. GitHub - nowork-studio/toprank: Open-source Claude Code skills for SEO, SEM, Google Ads GitHub - tacomanator/sash: Lightweight macOS menu bar app for reliably cycling through windows of the current application. Appents | Social Media Management for Product-First Teams GitHub - pnhoang/youtube-spam-blocker: Automatically detects and hides spam messages in YouTube Live chat. Set rate limits, keyword filters, and block repeat offenders. GitHub - decisionnode/DecisionNode: CLI + Local MCP - A shared structured memory store across Claude Code, Cursor, Windsurf, Antigravity, and every MCP client. Semantically queryable. GitHub - AvaCodeSolutions/django-email-learning: An open source Django app for creating email-based learning platforms with IMAP integration and React frontend components. The $100K Gap in Kubernetes Security Tooling Function Calling Harness: From 6.75% to 100%
Branchless Quicksort
Christof Kaser · 2026-05-19 · via Hacker News: Show HN

Fast Branchless Quicksort using Sorting-Networks with C++ Interface

On modern CPUs, avoiding branch misprediction is a key technique to speed up programs: When ‘if’ slows you down, avoid it.

Performance results naturally depend on the underlying hardware. The following benchmarks show the execution times for sorting 50 million doubles using different sorting implementations. The measurements were taken on an Apple M1 system using Clang and on an AMD Ryzen 3 system using GCC, both compiled with the -O3 option.

Implementation Apple M1 AMD Ryzen
std::sort 1.33s 5.56s
pdqsort 1.33s 2.81s
blqsort 1.01s 2.06s

blqsort

Full source code is included on the page in scrollable blocks and on Github.

This paper by Edelkamp and A. Weiß shows how partitioning performance in Quicksort can be improved by avoiding conditional branches.

The strategy of using an auxiliary buffer for branchless partitioning is inspired by fluxsort. The “auxiliary buffer” here means a 512‑element stack array, not heap memory.

To avoid the O(n²) runtime caused by bad input data, the program can group identical elements together and switch to heapsort for that specific part if it detects a big imbalance during partitioning. The program also checks if a partition is already sorted.

For larger parts, it uses a median-of-medians strategy to find a good pivot. In addition, critical partitioning loops are explicitly unrolled.

For 2 to 12 elements, the algorithm uses custom sorting networks. This approach requires a separate code path for each size but sorts small subsets with very few swaps using a branchless sort‑2 primitive. Source for sorting networks

As a result, blqsort becomes faster than, for example, std::sort and pdqsort for random numbers.

For types with higher copy or move costs (such as strings), the buffer-based branchless approach becomes less efficient. In this case, a BlockQuicksort variant is used, where only element indices are processed branchlessly, and the actual data is moved using fewer swap operations.

blqs.h

// SPDX-License-Identifier: MIT
// blqs.h - Branchless Quicksort
// (c) 2026 christof.kaser@gmail.com
//
// Fast generic sorting for arbitrary types with a C++ interface.
//
// Uses branchless partitioning and sorting networks for
// trivial types and BlockQuicksort (Edelkamp & Weiß) for
// complex types, with a fallback to heapsort.

#ifndef BLQS_H
#define BLQS_H

#include <cstddef>
#include <cstdint>
#include <type_traits>
#include <functional>
#include <utility>

namespace blqs {

template<typename T, typename Compare>
static inline void sort2(T& a, T& b, Compare comp) {
    T x = a; T y = b;
    bool m = comp(x, y);
    a = m ? x : y; b = m ? y : x;
}

template<typename T, typename Compare>
static inline void sort3(T& a, T& b, T& c, Compare comp) {
    sort2(a, b, comp); sort2(b, c, comp); sort2(a, b, comp);
}

template<typename T, typename Compare>
static inline void sort4(T& a, T& b, T& c, T& d, Compare comp) {
    sort2(a, b, comp); sort2(c, d, comp); sort2(a, c, comp);
    sort2(b, d, comp); sort2(b, c, comp);
}

template<typename T, typename Compare>
static inline void sort5(T& a, T& b, T& c, T& d, T& e, Compare comp) {
    sort2(b, c, comp); sort2(d, e, comp); sort2(b, d, comp);
    sort2(a, c, comp); sort2(a, d, comp); sort2(c, e, comp);
    sort2(a, b, comp); sort2(c, d, comp); sort2(b, c, comp);
}

template<typename T, typename Compare>
static inline void sort6(T& a, T& b, T& c, T& d, T& e, T& f, Compare comp) {
    sort2(a, b, comp); sort2(c, d, comp); sort2(e, f, comp);
    sort2(a, c, comp); sort2(b, d, comp); sort2(e, f, comp);
    sort2(a, e, comp); sort2(b, f, comp); sort2(c, e, comp);
    sort2(d, f, comp); sort2(b, c, comp); sort2(d, e, comp);
    sort2(c, d, comp);
}

template<typename T, typename Compare>
static inline void sort7(T& a, T& b, T& c, T& d, T& e, T& f, T& g, Compare comp) {
    sort2(a, g, comp); sort2(c, d, comp); sort2(e, f, comp);
    sort2(a, c, comp); sort2(b, e, comp); sort2(d, g, comp);
    sort2(a, b, comp); sort2(c, f, comp); sort2(d, e, comp);
    sort2(b, c, comp); sort2(e, g, comp);
    sort2(c, d, comp); sort2(e, f, comp);
    sort2(b, c, comp); sort2(d, e, comp); sort2(f, g, comp);
}

template<typename T, typename Compare>
static inline void sort8(T& a, T& b, T& c, T& d, T& e, T& f, T& g, T& h, Compare comp) {
    sort2(a,b,comp); sort2(c,d,comp); sort2(e,f,comp); sort2(g,h,comp);
    sort2(a,c,comp); sort2(b,d,comp); sort2(e,g,comp); sort2(f,h,comp);
    sort2(b,c,comp); sort2(f,g,comp);
    sort2(a,e,comp); sort2(b,f,comp); sort2(c,g,comp); sort2(d,h,comp);
    sort2(c,e,comp); sort2(d,f,comp);
    sort2(b,c,comp); sort2(d,e,comp); sort2(f,g,comp);
}

template<typename T, typename Compare>
static inline void sort9(T& a, T& b, T& c, T& d, T& e, T& f, T& g, T& h, T& i, Compare comp) {
    sort2(a,d,comp); sort2(b,h,comp); sort2(c,f,comp); sort2(e,i,comp);
    sort2(a,h,comp); sort2(c,e,comp); sort2(d,i,comp); sort2(f,g,comp);
    sort2(a,c,comp); sort2(b,d,comp); sort2(e,f,comp); sort2(h,i,comp);
    sort2(b,e,comp); sort2(d,g,comp); sort2(f,h,comp);
    sort2(a,b,comp); sort2(c,e,comp); sort2(d,f,comp); sort2(g,i,comp);
    sort2(c,d,comp); sort2(e,f,comp); sort2(g,h,comp);
    sort2(b,c,comp); sort2(d,e,comp); sort2(f,g,comp);
}

template<typename T, typename Compare>
static inline void sort10(T& a, T& b, T& c, T& d, T& e, T& f, T& g, T& h, T& i, T& j, Compare comp) {
    sort2(a,b,comp); sort2(c,f,comp); sort2(d,g,comp); sort2(e,h,comp); sort2(i,j,comp);
    sort2(a,g,comp); sort2(b,i,comp); sort2(c,e,comp); sort2(d,j,comp); sort2(f,h,comp);
    sort2(a,c,comp); sort2(b,d,comp); sort2(e,f,comp); sort2(g,i,comp); sort2(h,j,comp);
    sort2(a,b,comp); sort2(c,h,comp); sort2(d,f,comp); sort2(e,g,comp); sort2(i,j,comp);
    sort2(b,c,comp); sort2(d,e,comp); sort2(f,g,comp); sort2(h,i,comp);
    sort2(b,d,comp); sort2(c,e,comp); sort2(f,h,comp); sort2(g,i,comp);
    sort2(c,d,comp); sort2(e,f,comp); sort2(g,h,comp);
}

template<typename T, typename Compare>
static inline void sort11(T& a, T& b, T& c, T& d, T& e, T& f, T& g, T& h, T& i, T& j, T& k, Compare comp) {
    sort2(a,j,comp); sort2(b,g,comp); sort2(c,e,comp); sort2(d,h,comp); sort2(f,i,comp);
    sort2(a,b,comp); sort2(d,f,comp); sort2(e,k,comp); sort2(g,j,comp); sort2(h,i,comp);
    sort2(b,d,comp); sort2(c,f,comp); sort2(e,h,comp); sort2(i,k,comp);
    sort2(a,e,comp); sort2(b,c,comp); sort2(d,h,comp); sort2(f,j,comp); sort2(g,i,comp);
    sort2(a,b,comp); sort2(c,g,comp); sort2(e,f,comp); sort2(h,i,comp);
    sort2(j,k,comp);
    sort2(c,e,comp); sort2(d,g,comp); sort2(f,h,comp); sort2(i,j,comp);
    sort2(b,c,comp); sort2(d,e,comp); sort2(f,g,comp); sort2(h,i,comp);
    sort2(c,d,comp); sort2(e,f,comp); sort2(g,h,comp);
}

template<typename T, typename Compare>
static inline void sort12(T& a, T& b, T& c, T& d, T& e, T& f, T& g, T& h, T& i, T& j, T& k, T& l, Compare comp) {
    sort2(a,i,comp); sort2(b,h,comp); sort2(c,g,comp); sort2(d,l,comp); sort2(e,k,comp); sort2(f,j,comp);
    sort2(a,c,comp); sort2(b,e,comp); sort2(d,f,comp); sort2(g,i,comp); sort2(h,k,comp); sort2(j,l,comp);
    sort2(a,b,comp); sort2(c,j,comp); sort2(e,h,comp); sort2(f,g,comp); sort2(k,l,comp);
    sort2(b,d,comp); sort2(c,h,comp); sort2(e,j,comp); sort2(i,k,comp);
    sort2(a,b,comp); sort2(c,d,comp); sort2(e,f,comp); sort2(g,h,comp); sort2(i,j,comp); sort2(k,l,comp);
    sort2(b,c,comp); sort2(d,f,comp); sort2(g,i,comp); sort2(j,k,comp);
    sort2(c,e,comp); sort2(d,g,comp); sort2(f,i,comp); sort2(h,j,comp);
    sort2(b,c,comp); sort2(d,e,comp); sort2(f,g,comp); sort2(h,i,comp); sort2(j,k,comp);
}

template<typename T, typename Compare>
static inline void sorting_network(T* l, int partsz_min1, Compare comp) {
    switch (partsz_min1) {
        case 11: sort12(l[0],l[1],l[2],l[3],l[4],l[5],l[6],l[7],l[8],l[9],l[10],l[11],comp); break;
        case 10: sort11(l[0],l[1],l[2],l[3],l[4],l[5],l[6],l[7],l[8],l[9],l[10],comp); break;
        case 9:  sort10(l[0],l[1],l[2],l[3],l[4],l[5],l[6],l[7],l[8],l[9],comp); break;
        case 8:  sort9(l[0],l[1],l[2],l[3],l[4],l[5],l[6],l[7],l[8],comp); break;
        case 7:  sort8(l[0],l[1],l[2],l[3],l[4],l[5],l[6],l[7],comp); break;
        case 6:  sort7(l[0],l[1],l[2],l[3],l[4],l[5],l[6],comp); break;
        case 5:  sort6(l[0],l[1],l[2],l[3],l[4],l[5],comp); break;
        case 4:  sort5(l[0],l[1],l[2],l[3],l[4],comp); break;
        case 3:  sort4(l[0],l[1],l[2],l[3],comp); break;
        case 2:  sort3(l[0],l[1],l[2],comp); break;
        case 1:  sort2(l[0], l[1], comp); break;
        default: break;
    }
}

template<typename T, typename Compare>
void heap_sort(T* left, T* right, Compare comp) {
    long n = right - left + 1;
    if (n < 2) return;
    for (long i = n / 2; ; ) {
        T k;
        if (i > 0) k = left[--i];
        else {
            n -= 1; if (n == 0) return;
            k = left[n]; left[n] = left[0];
        }
        long j = i;
        while (j * 2 + 1 < n) {
            long child = j * 2 + 1;
            if (child + 1 < n && comp(left[child], left[child + 1])) child++;
            if (!comp(k, left[child])) break;
            left[j] = left[child]; j = child;
        }
        left[j] = k;
    }
}

template<typename T, typename Compare>
static inline void med5(T& a, T& b, T& c, T& d, T& e, Compare comp) {
    sort2(a, b, comp); sort2(c, d, comp);
    sort2(a, c, comp); sort2(b, d, comp);
    sort2(b, c, comp); sort2(c, e, comp);
    sort2(b, c, comp);
}

constexpr int SMALLPART = 256;
constexpr int SWSZ = 1024;
constexpr int UNROLL = 16;

template<typename T, typename Compare>
static T* partition_small(T* __restrict__ left, T* __restrict__ right, Compare comp) {
    T* outerleft = left;
    T* pivp = left + (right - left) / 2;
    med5(left[1], left[2], *pivp, right[-1], *right, comp);
    left += 3; right -= 2;
    T piv = *pivp; *pivp = *outerleft;

    T swbuf[SMALLPART];
    T *sw = swbuf, *lwr = left;
    while (left <= right) {
        bool h = comp(*left, piv);
        *lwr = *sw = *left++;
        lwr += h; sw += !h;
    }
    std::move(swbuf, sw, lwr);
    lwr -= 1; *outerleft = *lwr; *lwr = piv;
    return lwr;
}

template<typename T, typename Compare>
static T* partition_large(T* __restrict__ left, T* __restrict__ right, Compare comp) {
    T* outerleft = left;
    T* pivp = left + (right - left) / 2;

    med5(left[1], left[2], left[3], left[4], left[5], comp);
    med5(left[21], left[22], left[23], left[24], left[25], comp);
    med5(pivp[-2], pivp[-1], pivp[0], pivp[1], pivp[2], comp);
    med5(right[-14], right[-13], right[-12], right[-11], right[-10], comp);
    med5(right[-4], right[-3], right[-2], right[-1], right[0], comp);
    med5(left[3], left[23], pivp[0], right[-12], right[-2], comp);

    left += 1;
    T piv = *pivp; *pivp = *outerleft;

    while (comp(*left, piv)) left++;
    if (left >= outerleft + 12) {
        // could be sorted
        *pivp = piv;
        for (T* p = outerleft + 1; p <= right; p++) {
            if (comp(*p, *(p - 1))) {
                *pivp = *outerleft;
                goto not_sorted;
            }
        }
        return NULL;
    }
not_sorted:

    T swbuf[SWSZ];
    T *lwr = left, *rwr = right, *sw = swbuf;

    while (sw < swbuf + SWSZ - UNROLL && left <= right - UNROLL) {
        for (int i = UNROLL; i--;) {
            bool h = comp(*right, piv); *rwr = *sw = *right--; rwr -= !h; sw += h;
        }
    }
    while (sw < swbuf + SWSZ - UNROLL && left <= right) {
        bool h = comp(*right, piv); *rwr = *sw = *right--; rwr -= !h; sw += h;
    }
    while (left <= right - UNROLL) {
        while (rwr > right + UNROLL && left <= right - UNROLL) {
            for (int i = UNROLL; i--;) {
                bool h = comp(*left, piv); *lwr = *rwr = *left++; lwr += h; rwr -= !h;
            }
        }
        while (lwr < left - UNROLL && left <= right - UNROLL) {
            for (int i = UNROLL; i--;) {
                bool h = comp(*right, piv); *rwr = *lwr = *right--; rwr -= !h; lwr += h;
            }
        }
    }
    while (rwr > right && left <= right) {
        bool h = comp(*left, piv); *lwr = *rwr = *left++; lwr += h; rwr -= !h;
    }
    while (left <= right) {
        bool h = comp(*right, piv); *rwr = *lwr = *right--; rwr -= !h; lwr += h;
    }
    std::move(swbuf, sw, lwr);
    *outerleft = *rwr; *rwr = piv;
    return rwr;
}

template<typename T, typename Compare>
void blqsort(T* left, T* right, Compare comp) {
    while (1) {
        ptrdiff_t partszm1 = right - left;
        T* mid;

        if (partszm1 <= SMALLPART) {
            if (partszm1 <= 11) {
                sorting_network(left, (int)partszm1, comp);
                return;
            }
            mid = partition_small(left, right, comp);
        }
        else {
            mid = partition_large(left, right, comp);
            if (mid == NULL) return; // already sortiert

            if ((mid - left) * 16 < partszm1 || (right - mid) * 16 < partszm1) {
                heap_sort(left, mid - 1, comp);

                T piv = *mid;
                mid += 1;
                for (T* p = mid; p <= right; p++) {
                    if (!comp(piv, *p)) {
                        std::swap(*mid, *p);
                        mid++;
                    }
                }
                heap_sort(mid, right, comp);
                return;
            }
        }
        if (mid - left < right - mid) {
            blqsort(left, mid - 1, comp);
            left = mid + 1;
        } else {
            blqsort(mid + 1, right, comp);
            right = mid - 1;
        }
    }
}

template <typename T, typename Compare>
static inline void insert_sort(T* left, T* right, Compare comp) {
    for (T* i = left + 1; i <= right; i++) {
        T key = std::move(*i);
        T* j = i;
        while (j > left && comp(key, *(j - 1))) {
            *j = std::move(*(j - 1));
            j--;
        }
        *j = std::move(key);
    }
}

template <typename T, typename Compare>
static inline void med3(T* a, T* b, T* c, Compare comp) {
    if (comp(*b, *a)) std::swap(*a, *b);
    if (comp(*c, *a)) std::swap(*a, *c);
    if (comp(*c, *b)) std::swap(*b, *c);
}

// Based on BlockQuicksort by Edelkamp and Weiß

template <typename T, typename Compare>
void block_qsort(T* left0, T* right0, Compare comp) {

    constexpr long BLSZ = 512;

    while (right0 - left0 > 16) {

        size_t sizem1 = right0 - left0;
        T* mid = left0 + sizem1 / 2;

        T* left = left0 + 1;
        T* right = right0;

        if (sizem1 > 64) {
            med3(left, left + 1, left + 2, comp);
            med3(mid - 1, mid, mid + 1, comp);
            med3(right - 2, right - 1, right, comp);
            med3(left + 1, mid, right - 1, comp);
        }
        else {
            med3(left, mid, right, comp);
            left += 1;
            right -= 1;
        }

        T pivot = std::move(*mid);
        *mid = std::move(*left0);

        T* left_p[BLSZ];
        T* right_p[BLSZ];

        int nleft = 0;
        int nright = 0;
        int left_offs, right_offs;

        while (right >= left) {
            int blsz = std::min(BLSZ, right - left + 1);
            if (nleft == 0) {
                for (T* endl = left + blsz; left < endl; left++) {
                    left_p[nleft] = left;
                    nleft += !comp(*left, pivot);
                }
                left_offs = 0;
            }
            else {
                for (T* endr = right - blsz; right > endr; right--) {
                    right_p[nright] = right;
                    nright += !comp(pivot, *right);
                }
                right_offs = 0;
            }
            int nswaps = std::min(nleft, nright);
            for (int k = 0; k < nswaps; k++) {
                std::iter_swap(left_p[left_offs], right_p[right_offs]);
                left_offs++;
                right_offs++;
            }
            nleft -= nswaps;
            nright -= nswaps;
        }
        if (nleft) {
            for (int k = left_offs + nleft - 1; k >= left_offs; k--, right--) {
                std::iter_swap(left_p[k], right);
            }
        }
        else {
            for (int k = right_offs + nright - 1; k >= right_offs; k--, left++) {
                std::iter_swap(right_p[k], left);
            }
            right = left - 1;
        }
        *left0 = std::move(*right);
        *right = std::move(pivot);

        ptrdiff_t szl = right - left0;
        ptrdiff_t szr = right0 - right;
        ptrdiff_t szmin = (szl < szr) ? szl : szr;

        if (szmin * 16 < right0 - left0) {
            heap_sort(left0, right - 1, comp);
            heap_sort(right + 1, right0, comp);
            return;
        }
        if (szl < szr) {
            block_qsort(left0, right - 1, comp);
            left0 = right + 1;
        } else {
            block_qsort(right + 1, right0, comp);
            right0 = right - 1;
        }
    }
    insert_sort(left0, right0, comp);
}

template <typename T, typename Compare = std::less<T>>
void sort(T* first, T* last, Compare comp = Compare()) {

    if (last - first < 2) return;

    constexpr bool copy_is_cheap =
        std::is_trivially_copyable<T>::value && sizeof(T) <= 16;

    if constexpr (copy_is_cheap) {
        blqsort(first, last - 1, comp);
    }
    else {
        block_qsort(first, last - 1, comp);
    }
}
}
#endif
You only need to include this single header file, and it can be used just as easily as std::sort.
#include <cstdio>
#include <cstdlib>
#include <ctime>

#include "blqs.h"

constexpr int SIZE = 50000000;

double data[SIZE];

double cputime() {
    return (double)clock() / CLOCKS_PER_SEC;
}
int main() {
    double t0;
    printf("blqs::sort - sorting %d million doubles ...\n", SIZE / 1000000);

    for (int i = 0; i < SIZE; i++) data[i] = rand() / 1024.0;
    t0 = cputime();
    blqs::sort(data, data + SIZE);
    printf("Random: %.2fs\n", cputime() - t0);

    t0 = cputime();
    blqs::sort(data, data + SIZE);
    printf("Sorted: %.2fs\n", cputime() - t0);

    for (int i = 0; i < 10; i++) std::swap(data[rand() % (SIZE / 10)], data[rand() % (SIZE / 10)]);
    t0 = cputime();
    blqs::sort(data, data + SIZE);
    printf("Nearly sorted: %.2fs\n", cputime() - t0);

    for (int i = 0; i < SIZE; i++) data[i] = rand() % 1000;
    t0 = cputime();
    blqs::sort(data, data + SIZE);
    printf("Duplicates: %.2fs\n", cputime() - t0);
}
g++ -std=c++17 -O3 test.cpp && ./a.out
blqsort - sorting 50 million doubles ...
Random: 1.01s
Sorted: 0.03s
Nearly sorted: 0.13s
Duplicates: 0.51s
With std::sort and pdqsort (which interestingly has almost exactly the same runtimes), it looks like this:
std::sort - sorting 50 million doubles ...
Random: 1.33s
Sorted: 0.05s
Nearly sorted: 0.07s
Duplicates: 0.28s

Sorting Custom Data Structures

In practice, we often need to sort custom data structures. This is where SIMD libraries like Google Highway - while very fast for simple numbers - become difficult to use.

Using std::sort or blqs::sort gives you much more flexibility;

#include <cstdio>
#include <cstdlib>
#include <ctime>

#include "blqs.h"

constexpr int SIZE = 50000000;

struct entry {
    int32_t id;
    int32_t value;
    bool operator<(const entry& other) const {
        return id < other.id;
    }
};

struct entry data[SIZE];

double cputime() {
    return (double)clock() / CLOCKS_PER_SEC;
}
int main() {
    double t0;
    printf("blqs::sort - sorting %d million structs ...\n", SIZE / 1000000);
    for (int i = 0; i < SIZE; i++) data[i].id = rand();
    t0 = cputime();
    blqs::sort(data, data + SIZE);
    printf("Time: %.2fs\n", cputime() - t0);
}
Execution times for sorting 50 million of this structs.
Implementation Apple M1 AMD Ryzen
std::sort 3.46s 4.75s
pdqsort 3.46s 4.72s
blqsort 0.97s 2.20s

Branchless Quicksort in C

Multi-Threaded Sorting in C

Interactive Sorting Demo


christof.kaser@gmail.com