natsort

natsort(array &$array): true

Natural order: digit segments compare by value (img2 < img10), text segments lexically; key-value bindings kept; natcasesort is the case-insensitive variant.

C C23

C23
#include <ctype.h>
#include <stdio.h>

/* Hand-written natural comparison: digit runs by value, text runs lexically
   (the C standard library has no strnatcmp) */
static int natcmp(const char *a, const char *b) {
    while (*a && *b) {
        if (isdigit((unsigned char)*a) && isdigit((unsigned char)*b)) {
            long na = 0, nb = 0;
            while (isdigit((unsigned char)*a)) { na = na * 10 + (*a - '0'); a++; }
            while (isdigit((unsigned char)*b)) { nb = nb * 10 + (*b - '0'); b++; }
            if (na != nb) return na < nb ? -1 : 1;
        } else {
            if (*a != *b) return *a < *b ? -1 : 1;
            a++; b++;
        }
    }
    return (unsigned char)*a - (unsigned char)*b;
}

int main(void) {
    const char *imgs[] = {"img12.png", "img10.png", "img2.png", "img1.png"};
    for (int i = 1; i < 4; i++) {
        const char *key = imgs[i];
        int j = i - 1;
        while (j >= 0 && natcmp(imgs[j], key) > 0) { imgs[j + 1] = imgs[j]; j--; }
        imgs[j + 1] = key;
    }
    for (int i = 0; i < 4; i++) printf("%s\n", imgs[i]);
    return 0;
}
Output
img1.png
img2.png
img10.png
img12.png

C++ C++26

C++26
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
#include <vector>

// Hand-written natural comparison: digit runs by value, text runs lexically
static int natcmp(const std::string &a, const std::string &b) {
    size_t i = 0, j = 0;
    while (i < a.size() && j < b.size()) {
        if (std::isdigit(static_cast<unsigned char>(a[i])) &&
            std::isdigit(static_cast<unsigned char>(b[j]))) {
            long na = 0, nb = 0;
            while (i < a.size() && std::isdigit(static_cast<unsigned char>(a[i]))) {
                na = na * 10 + (a[i++] - '0');
            }
            while (j < b.size() && std::isdigit(static_cast<unsigned char>(b[j]))) {
                nb = nb * 10 + (b[j++] - '0');
            }
            if (na != nb) return na < nb ? -1 : 1;
        } else {
            if (a[i] != b[j]) return a[i] < b[j] ? -1 : 1;
            i++; j++;
        }
    }
    if (a.size() - i != b.size() - j) return a.size() - i < b.size() - j ? -1 : 1;
    return 0;
}

int main() {
    std::vector<std::string> imgs = {"img12.png", "img10.png", "img2.png", "img1.png"};
    std::sort(imgs.begin(), imgs.end(), natcmp);
    for (const auto &s : imgs) std::cout << s << "\n";
    return 0;
}
Output
img1.png
img2.png
img10.png
img12.png

C# v11.0.100

v11.0.100
// No built-in natural sort: hand-write a segmented comparison -
// digit runs by value, text runs lexically
int NaturalCompare(string a, string b)
{
    int i = 0, j = 0;
    while (i < a.Length && j < b.Length)
    {
        char ca = a[i], cb = b[j];
        if (char.IsDigit(ca) && char.IsDigit(cb))
        {
            long na = 0, nb = 0;
            while (i < a.Length && char.IsDigit(a[i])) na = na * 10 + (a[i++] - '0');
            while (j < b.Length && char.IsDigit(b[j])) nb = nb * 10 + (b[j++] - '0');
            if (na != nb) return na.CompareTo(nb);
        }
        else
        {
            if (ca != cb) return ca - cb;
            i++; j++;
        }
    }
    return (a.Length - i) - (b.Length - j);
}

var imgs = new List<string> { "img12.png", "img10.png", "img2.png", "img1.png" };
imgs.Sort((x, y) => NaturalCompare(x, y));
Console.WriteLine("[" + string.Join(", ", imgs) + "]");
Console.WriteLine("[" + string.Join(", ", new List<string> { "img10.png", "img2.png" }.OrderBy(x => x, StringComparer.Ordinal)) + "]");
Output
[img1.png, img2.png, img10.png, img12.png]
[img10.png, img2.png]

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"sort"
	"strconv"
)

func isDigit(c byte) bool { return c >= '0' && c <= '9' }

func scanNumber(s string, i int) (int64, int) {
	start := i
	for i < len(s) && isDigit(s[i]) {
		i++
	}
	n, _ := strconv.ParseInt(s[start:i], 10, 64)
	return n, i
}

// naturalLess compares digit runs by value, text runs byte by byte
func naturalLess(a, b string) bool {
	i, j := 0, 0
	for i < len(a) && j < len(b) {
		da, db := isDigit(a[i]), isDigit(b[j])
		switch {
		case da && db:
			na, ai := scanNumber(a, i)
			nb, bj := scanNumber(b, j)
			if na != nb {
				return na < nb
			}
			i, j = ai, bj
		default:
			if a[i] != b[j] {
				return a[i] < b[j]
			}
			i++
			j++
		}
	}
	return len(a)-i < len(b)-j
}

func main() {
	imgs := []string{"img12.png", "img10.png", "img2.png", "img1.png"}
	sort.Slice(imgs, func(p, q int) bool { return naturalLess(imgs[p], imgs[q]) })
	fmt.Println(imgs)
	fmt.Println([]string{"img10.png", "img2.png"})
}
Output
[img1.png img2.png img10.png img12.png]
[img10.png img2.png]

Java v27.0.1

v27.0.1
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    // No built-in natural sort: hand-write a segmented comparator -
    // digit runs by value, text runs lexically
    static int naturalCompare(String a, String b) {
        int i = 0, j = 0;
        while (i < a.length() && j < b.length()) {
            char ca = a.charAt(i), cb = b.charAt(j);
            if (Character.isDigit(ca) && Character.isDigit(cb)) {
                long na = 0, nb = 0;
                while (i < a.length() && Character.isDigit(a.charAt(i))) {
                    na = na * 10 + (a.charAt(i++) - '0');
                }
                while (j < b.length() && Character.isDigit(b.charAt(j))) {
                    nb = nb * 10 + (b.charAt(j++) - '0');
                }
                if (na != nb) return Long.compare(na, nb);
            } else {
                if (ca != cb) return ca - cb;
                i++; j++;
            }
        }
        return (a.length() - i) - (b.length() - j);
    }

    public static void main(String[] args) {
        List<String> imgs = new ArrayList<>(Arrays.asList("img12.png", "img10.png", "img2.png", "img1.png"));
        imgs.sort(Main::naturalCompare);
        System.out.println(imgs);
        System.out.println(Arrays.asList("img10.png", "img2.png"));
    }
}
Output
[img1.png, img2.png, img10.png, img12.png]
[img10.png, img2.png]

JavaScript v26.13.1

v26.13.1
// localeCompare with { numeric: true } is the built-in natural order
const nat = (a, b) => a.localeCompare(b, undefined, { numeric: true });
console.log(["img12.png", "img10.png", "img2.png", "img1.png"].sort(nat));
console.log(["a5", "a40", "a1"].sort(nat));
// Contrast: plain string order - "img10" < "img2"
console.log(["img10.png", "img2.png"].sort());
Output
[ 'img1.png', 'img2.png', 'img10.png', 'img12.png' ]
[ 'a1', 'a5', 'a40' ]
[ 'img10.png', 'img2.png' ]

PHP v8.6.0

v8.6.0
// Natural order: numeric segments compare by value ("img2" < "img10");
// keys stay bound to their values
$img = ['img12.png', 'img10.png', 'img2.png', 'img1.png'];
natsort($img);
echo json_encode($img), "\n";
natcasesort($img);
$img2 = ['IMG10', 'img2', 'IMG1'];
natcasesort($img2);
echo json_encode(array_values($img2)), "\n";
// Contrast: the default sort compares ordinary strings - "img10" < "img2"
$m = ['img10.png', 'img2.png'];
sort($m);
echo json_encode($m);
Output
{"3":"img1.png","2":"img2.png","1":"img10.png","0":"img12.png"}
["IMG1","img2","IMG10"]
["img10.png","img2.png"]

Python v3.15.2

v3.15.2
import re

def natural_key(s):
    # Segment into digit/text runs; digit runs compare by value
    return [int(part) if part.isdigit() else part for part in re.split(r"(\d+)", s)]

imgs = ["img12.png", "img10.png", "img2.png", "img1.png"]
print(sorted(imgs, key=natural_key))
print(sorted(["a5", "a40", "a1"], key=natural_key))
# Contrast: plain string order - "img10" < "img2"
print(sorted(["img10.png", "img2.png"]))
Output
['img1.png', 'img2.png', 'img10.png', 'img12.png']
['a1', 'a5', 'a40']
['img10.png', 'img2.png']

Rust v1.99.1

v1.99.1
use std::cmp::Ordering;

// Segment into (is_digit, chunk) runs: digits compare by value,
// text runs lexically
fn natural_cmp(a: &str, b: &str) -> Ordering {
    let segs = |s: &str| -> Vec<(bool, String)> {
        let mut out = Vec::new();
        let mut cur = String::new();
        let mut cur_digit = false;
        for ch in s.chars() {
            let d = ch.is_ascii_digit();
            if !cur.is_empty() && d != cur_digit {
                out.push((cur_digit, std::mem::take(&mut cur)));
            }
            cur_digit = d;
            cur.push(ch);
        }
        if !cur.is_empty() {
            out.push((cur_digit, cur));
        }
        out
    };
    let ka = segs(a);
    let kb = segs(b);
    for (sa, sb) in ka.iter().zip(kb.iter()) {
        if sa.0 && sb.0 {
            let na: u64 = sa.1.parse().unwrap();
            let nb: u64 = sb.1.parse().unwrap();
            if na != nb {
                return na.cmp(&nb);
            }
        } else if sa.1 != sb.1 {
            return sa.1.cmp(&sb.1);
        }
    }
    ka.len().cmp(&kb.len())
}

fn main() {
    // Rust has no built-in natural sort (the natord crate exists): segment
    // keys by hand - digit runs by value, text runs lexically
    let mut imgs = vec!["img12.png", "img10.png", "img2.png", "img1.png"];
    imgs.sort_by(|a, b| natural_cmp(a, b));
    println!("{:?}", imgs);
    println!("{:?}", vec!["img10.png", "img2.png"]);
}
Output
["img1.png", "img2.png", "img10.png", "img12.png"]
["img10.png", "img2.png"]

TypeScript v26.13.1

v26.13.1
// localeCompare with { numeric: true } is the built-in natural order
const nat = (a: string, b: string): number =>
    a.localeCompare(b, undefined, { numeric: true });
console.log(["img12.png", "img10.png", "img2.png", "img1.png"].sort(nat));
console.log(["a5", "a40", "a1"].sort(nat));
console.log(["img10.png", "img2.png"].sort());
Output
[ 'img1.png', 'img2.png', 'img10.png', 'img12.png' ]
[ 'a1', 'a5', 'a40' ]
[ 'img10.png', 'img2.png' ]

Language differences

C: the standard library has no strnatcmp - hand-write segmented comparison (digit runs to numbers, text runs byte-wise); the famous implementation is Martin Pool's strnatcmp.c (the same algorithm as GNU coreutils ls -v).

C++: same hand-writing as C; std::ranges can help segment, but nothing built-in at the language/stdlib level.

C#: no built-in - hand-written segmented comparison; the StringComparer family offers ordinal/culture orders only, no numeric semantics.

Go: no built-in - hand-written segmented comparison (this example scans digit runs into int64); third-party options like facette.io/natsort.

Java: no built-in - hand-written segmented Comparator (digit runs as long to avoid int overflow); no commons-lang3 support, only niche third-party libs.

JavaScript: native support - localeCompare(other, undefined, { numeric: true }) (ECMA-402 Intl semantics), the only built-in natural order among the ten languages; add sensitivity: "accent" for case-insensitivity.

PHP: natsort compares digit runs by value and keeps key-value bindings (returns true, sorts in place; the return type narrowed from bool to true in PHP 8.3); natcasesort is the case-insensitive variant; neither is a true sort function - on failure the array is left unsorted (per the manual).

Python: no built-in - the third-party natsort library or a hand-written regex segmented key (re.split(r"(\d+)", s) alternating segments with int segments) - "segmented keys" are the universal teaching point across languages: digits by value, letters lexicographically.

Rust: no built-in (the natord crate provides the same algorithm) - this example hand-writes segmented keys; sort_by + Ordering maps directly.

TypeScript: same as JavaScript - localeCompare({ numeric: true }) natively; nothing new at the type level.