← Retour au blog
tech 5 June 2026

Branchless Quicksort: Faster than std::sort and pdqsort with C and C++ API

Discover how branchless Quicksort outperforms std::sort and pdqsort using sorting networks. An optimized approach for modern CPUs, with impressive benchmarks on Apple M1 and AMD Ryzen.

Article inspired by the original source
Branchless Quicksort faster than std:sort and pdqsort with C and C++ API ↗ tiki.li

Introduction

In the realm of sorting algorithm optimization, branchless Quicksort stands out by surpassing traditional methods like std::sort and pdqsort. By leveraging modern processors' capabilities, this approach reduces branch mispredictions, resulting in significant performance gains.

Why Avoid Branches?

Modern CPUs are designed to execute instructions in parallel, but conditional branches can disrupt this flow. A branch misprediction can incur significant penalties. By avoiding branches, branchless Quicksort ensures a smoother and faster execution flow.

Code Example

Consider two versions of the same code:

```c // Version with branch for (int i = 0; i < 1000; i++) { if (numbers[i] < 500) { small_numbers[smlen] = numbers[i]; smlen += 1; } }

// Branchless version for (int i = 0; i < 1000; i++) { small_numbers[smlen] = numbers[i]; smlen += (numbers[i] < 500); } ```

The branchless version is more efficient because it avoids the branch predictions that slow down execution.

Implementation and Benchmarks

On an Apple M1 system, branchless Quicksort sorts 50 million doubles in just 0.97 seconds, compared to 1.33 seconds for std::sort. On an AMD Ryzen processor, the results are equally impressive with 2.06 seconds for branchless Quicksort versus 5.56 seconds for std::sort.

Technical Details

The implementation uses a 1024-element auxiliary buffer for branchless partitioning, inspired by fluxsort. Using sorting networks for sizes from 2 to 12 elements minimizes the necessary swaps.

Pivot Strategy and Handling Bad Cases

To avoid the O(n²) runtime caused by bad input data, branchless Quicksort groups identical elements and switches to heapsort if a significant imbalance is detected. It also uses a median-of-medians strategy to select a good pivot.

Conclusion

Branchless Quicksort represents a significant advancement in sorting algorithms, offering superior performance through better CPU resource management. For developers looking to optimize their applications, it's an indispensable option.

Let's discuss your project in 15 minutes.

branchless quicksort sorting algorithms C++ optimization CPU performance algorithm benchmarking
Deepthix newsletter · 100% AI · every Monday 8am

An AI agent reads tech for you.

Our AI agent scans ~200 sources per week and ships the best articles to your inbox Monday 8am. Free. One click to unsubscribe.

Visit the newsletter page →

Want to automate your operations?

Let's talk about your project in 15 minutes.

Book a call