Natural Order Sort For Numbered Names
Sort versioned names like backup-10 after backup-9 by comparing digit runs numerically instead of lexicographically with a Character.isDigit scan.
Code
import java.util.ArrayList;
import java.util.List;
public class NaturalOrderSort {
// Digit runs compare numerically, everything else character by character: numbered names order backup-10 after backup-9
static int naturalCompare(String a, String b) {
int i = 0;
int j = 0;
while (i < a.length() && j < b.length()) {
char ca = a.charAt(i);
char cb = b.charAt(j);
if (Character.isDigit(ca) && Character.isDigit(cb)) {
int startA = i;
int startB = j;
while (i < a.length() && Character.isDigit(a.charAt(i))) i++;
while (j < b.length() && Character.isDigit(b.charAt(j))) j++;
int byNumber = Long.compare(
Long.parseLong(a, startA, i, 10),
Long.parseLong(b, startB, j, 10));
if (byNumber != 0) {
return byNumber;
}
} else if (ca != cb) {
return Character.compare(ca, cb);
} else {
i++;
j++;
}
}
return Integer.compare(a.length() - i, b.length() - j);
}
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of(
"backup-9.zip", "backup-10.zip", "backup-1.zip",
"backup-23b.zip", "backup-23a.zip"));
names.sort(NaturalOrderSort::naturalCompare);
names.forEach(System.out::println);
}
}How it works
Structurally, expect the class NaturalOrderSort and the functions naturalCompare and main and nothing else.
The file repeats itself only inside while (i < a.length() && j < b.length()).
What to watch for
- The toolchain alone is enough — no dependency resolution happens.
Using it
The primary signature is static int naturalCompare(String a, String b)
Key statements
return Integer.compare(a.length() - i, b.length() - j);
names.sort(NaturalOrderSort::naturalCompare);
return Character.compare(ca, cb);
Interactive Tools for This Topic
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.
FAQ
- How do you run Natural Order Sort For Numbered Names?
- The file is self-contained: run it directly, no dependencies to install beforehand.
Report a problem with this exampleOpens a pre-filled issue on GitHub.