Comparison vs non-comparison sorting
Advanced · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Comparison sorts decide order by asking which of two items is bigger, and they work on any kind of data. Non-comparison sorts, such as counting and radix sort, place items by their value directly, which is faster but only works for certain kinds of keys.
Practical use cases
- Web app: Choosing a sort for two different jobs. A school portal sorts students by name and also by marks from 0 to 100. Names need a general comparison sort, since there are endless possibilities. The marks fit a counting sort with 101 counters, which ranks lakhs of students much faster.
- Web app: Sorting fixed-length order ids. An e-commerce back office sorts millions of order numbers that are all exactly 10 digits. A digit-by-digit method can beat a general sort here, because it never needs to compare whole numbers. On a small list, though, the built-in sort is still the simpler and safer choice.
- System: Particle ordering in games. Game engines draw thousands of particles and must order them by small depth values. Placing them into depth buckets directly is faster than comparing every pair, so frames stay smooth and players never see a stutter.
The story: The Balance and the Bins
Mira and Kabir were sorting a bag of different-weight stones at the village fair. Mira used an old balance scale: put two stones on it, see which is heavier. She had to weigh stones against stones again and again. It worked for any stones, but it was slow.
Kabir looked at the stones and saw that each one had a number painted on it, from 1 to 10. "Why do I need the scale?", he said. He put out ten bins labelled 1 to 10 and tossed each stone into the bin with its own number. A moment later the stones were sorted. No weighing at all!
Mrs. Sharma used this to explain two families of sorting. A comparison sort (like Mira's balance) only learns about the data by asking "which of these two is bigger?". It works for anything you can compare, but cannot go faster than about n log n steps.
A non-comparison sort (like Kabir's bins) looks inside the values, such as digits or small whole numbers, and uses them directly. It can run in nearly straight-line time, but only when the data has the right shape.
How to spot this problem, and where you need it
You are choosing how to sort a big list and want to know if the speed of a general sort is the best you can do, or whether the type of data allows a faster trick.
Signs you need it
- The keys are small whole numbers, fixed-length codes or values in a known range, such as ages, marks, pincodes or ratings.
- The data is free text, custom objects or anything compared by your own rule, so only comparisons make sense.
- A general sort takes too long on millions of simple keys, such as 10-digit ids, and profiling shows the sort is the slow step.
Where to use it in a project
- Ranking exam marks or ratings, where counting sort fits, versus names or mixed fields, where the built-in sort is the right choice.
- Batch processing of fixed-length ids, dates or pincodes before grouping.
The solution
Look at the keys first. If they are free-form, such as names or objects with custom rules, use the built-in comparison sort, which is well tested and fast enough. If they are small whole numbers or fixed-length codes, consider counting or radix sort, which skip comparisons and finish in a few passes. When in doubt, start with the built-in sort and switch only if measurement shows it is the bottleneck.
Payoff: Before: 10 lakh marks sorted by comparing pairs. After: one counting pass over 101 buckets, and the result list is ready almost instantly.
Explain it like I am 8
A balance scale tells you which of two things is heavier, but you must weigh over and over. Labelled bins let you put each thing straight where it belongs without weighing. Bins are quicker, but you can only use them when things have a number you can read.
How it works, step by step
- Comparison sorts only use the question "is a smaller than b?" They work on any data you can compare (numbers, names, dates).
- Their speed limit is about n log n in the worst case. Merge sort and heap sort reach it.
- Non-comparison sorts use the value itself (digits, small integers) to place items directly.
- Counting, radix and bucket sort are non-comparison sorts and can reach O(n) time on the right data.
- Choose by data: unknown type or huge range means comparison. Small whole-number range or fixed-length keys means non-comparison.
The code in four languages
PHP
<?php
// Comparison sort: insertion sort that COUNTS how many "is a bigger than b?" questions it asks.
function insertionWithCount(array $a): array {
$compares = 0;
for ($i = 1; $i < count($a); $i++) {
$key = $a[$i];
$j = $i - 1;
while ($j >= 0) {
$compares++; // one comparison question
if ($a[$j] > $key) { $a[$j + 1] = $a[$j]; $j--; }
else break;
}
$a[$j + 1] = $key;
}
return [$a, $compares];
}
// Non-comparison sort: counting sort. It never compares two items, it uses the value as a shelf number.
function countingNoCompare(array $a, int $maxValue): array {
$shelves = array_fill(0, $maxValue + 1, 0);
foreach ($a as $v) $shelves[$v]++;
$out = [];
foreach ($shelves as $v => $c) for ($k = 0; $k < $c; $k++) $out[] = $v;
return [$out, 0];
}
$tokens = [4, 2, 5, 1, 3, 5, 2];
[$s1, $c1] = insertionWithCount($tokens);
[$s2, $c2] = countingNoCompare($tokens, 5);
echo 'Comparison: ', implode(',', $s1), ' (', $c1, " comparisons)\n";
echo 'Non-comparison: ', implode(',', $s2), ' (', $c2, " comparisons)\n";JavaScript
// Comparison sort: insertion sort that COUNTS how many "is a bigger than b?" questions it asks.
function insertionWithCount(input) {
const a = [...input];
let compares = 0;
for (let i = 1; i < a.length; i++) {
const key = a[i];
let j = i - 1;
while (j >= 0) {
compares++; // one comparison question
if (a[j] > key) { a[j + 1] = a[j]; j--; }
else break;
}
a[j + 1] = key;
}
return [a, compares];
}
// Non-comparison sort: counting sort. It never compares two items, it uses the value as a shelf number.
function countingNoCompare(a, maxValue) {
const shelves = new Array(maxValue + 1).fill(0);
for (const v of a) shelves[v]++;
const out = [];
shelves.forEach((c, v) => { for (let k = 0; k < c; k++) out.push(v); });
return [out, 0];
}
const tokens = [4, 2, 5, 1, 3, 5, 2];
const [s1, c1] = insertionWithCount(tokens);
const [s2, c2] = countingNoCompare(tokens, 5);
console.log('Comparison: ' + s1.join(',') + ' (' + c1 + ' comparisons)');
console.log('Non-comparison: ' + s2.join(',') + ' (' + c2 + ' comparisons)');Java
import java.util.*;
import java.util.stream.*;
public class Main {
// Comparison sort: insertion sort that COUNTS how many "is a bigger than b?" questions it asks.
static int insertionWithCount(int[] a) {
int compares = 0;
for (int i = 1; i < a.length; i++) {
int key = a[i];
int j = i - 1;
while (j >= 0) {
compares++; // one comparison question
if (a[j] > key) { a[j + 1] = a[j]; j--; }
else break;
}
a[j + 1] = key;
}
return compares;
}
// Non-comparison sort: counting sort. It never compares two items, it uses the value as a shelf number.
static int[] countingNoCompare(int[] a, int maxValue) {
int[] shelves = new int[maxValue + 1];
for (int v : a) shelves[v]++;
int[] out = new int[a.length];
int pos = 0;
for (int v = 0; v < shelves.length; v++) {
for (int k = 0; k < shelves[v]; k++) out[pos++] = v;
}
return out;
}
static String join(int[] a) {
return Arrays.stream(a).mapToObj(String::valueOf).collect(Collectors.joining(","));
}
public static void main(String[] args) {
int[] tokens = {4, 2, 5, 1, 3, 5, 2};
int[] s1 = tokens.clone(); // sort a copy so the input stays intact
int c1 = insertionWithCount(s1);
int[] s2 = countingNoCompare(tokens, 5);
System.out.println("Comparison: " + join(s1) + " (" + c1 + " comparisons)");
System.out.println("Non-comparison: " + join(s2) + " (0 comparisons)");
}
}Go
package main
import (
"fmt"
"strconv"
"strings"
)
// Comparison sort: insertion sort that COUNTS how many "is a bigger than b?" questions it asks.
func insertionWithCount(input []int) ([]int, int) {
a := append([]int(nil), input...)
compares := 0
for i := 1; i < len(a); i++ {
key := a[i]
j := i - 1
for j >= 0 {
compares++ // one comparison question
if a[j] > key {
a[j+1] = a[j]
j--
} else {
break
}
}
a[j+1] = key
}
return a, compares
}
// Non-comparison sort: counting sort. It never compares two items, it uses the value as a shelf number.
func countingNoCompare(a []int, maxValue int) ([]int, int) {
shelves := make([]int, maxValue+1)
for _, v := range a {
shelves[v]++
}
out := []int{}
for v, c := range shelves {
for k := 0; k < c; k++ {
out = append(out, v)
}
}
return out, 0
}
func join(a []int) string {
parts := make([]string, len(a))
for i, v := range a {
parts[i] = strconv.Itoa(v)
}
return strings.Join(parts, ",")
}
func main() {
tokens := []int{4, 2, 5, 1, 3, 5, 2}
s1, c1 := insertionWithCount(tokens)
s2, c2 := countingNoCompare(tokens, 5)
fmt.Printf("Comparison: %s (%d comparisons)\n", join(s1), c1)
fmt.Printf("Non-comparison: %s (%d comparisons)\n", join(s2), c2)
}Time: Comparison: O(n log n) at best. Non-comparison: about O(n) · Extra space: Comparison: often small. Non-comparison: needs extra space. The n log n wall only applies to sorts that learn by comparing. Reading the values directly lets counting, radix and bucket sort slip past it, with conditions.
Watch out for
- Believing "O(n log n) is the best any sorting can do". That is true only for comparison sorts.
- Using a non-comparison sort on data with a huge or unknown range, such as arbitrary decimals or long strings.
- Forgetting that non-comparison sorts trade memory (tally arrays, buckets) for speed.
Quick check
- Which of these is a non-comparison sort?
- Counting sort
- Quick sort
- Merge sort
- What is the best possible worst-case speed for any comparison sort?
- About n log n
- Exactly n
- Constant time
- You must sort a million names (text). Which family is usually the safest choice?
- Counting sort
- Comparison sort
- Neither is possible