In computing,natural sort order (ornatural sorting) is a way of ordering strings that treats embedded numbers as whole numerical values rather than sequences of characters.
While standardalphabetical order compares strings character-by-character (where "10" sorts before "2" because "1" is less than "2"), natural sort order orders them by magnitude of the number, placing "2" before "10".
Natural sort order is designed to address the shortcoming of standardlexicographical order, which often produces counter-intuitive results for humans when dealing with numbered lists, filenames, or version numbers.[1]
| Natural | Lexicographical |
|---|---|
| 1.jpg 2.jpg 3.jpg 9.jpg 10.jpg 11.jpg | 1.jpg 10.jpg 11.jpg 2.jpg 3.jpg 9.jpg |
In standard alphabetical (lexicographical) sorting, strings are compared character by character from left to right. This causes numbers to be sorted based on the value of their first digit, rather than their whole numerical value.
For example, a computer using standard sorting will place the string "11" before "2". This occurs because the character "1" (the first digit of 11) has a lower code value than "2". While mathematically correct in terms of character codes, this ordering disrupts the logical sequence expected by users, particularly in file management and data lists.
Natural sorting algorithms generally operate by splitting strings into "chunks" of text and numbers.
| Standard Sorting (Lexicographical) | Natural Sorting |
|---|---|
| file1.txt file10.txt file11.txt file12.txt file2.txt file20.txt file3.txt | file1.txt file2.txt file3.txt file10.txt file11.txt file12.txt file20.txt |
Different implementations of natural sort may handle edge cases differently:
Functionality to sort by natural sort order is now widely available in software libraries for many programming languages and operating systems.
The concept gained significant visibility in the Macintosh community. During the 1996MacHack conference, the Natural OrderMac OSSystem Extension was conceived and implemented overnight as an entry for the Best Hack contest.[2][3] Subsequently, Dave Koelle published the "Alphanum Algorithm" in 1997,[4] a popular reference implementation that influenced many later libraries. Martin Pool published "Natural Order String Comparison" in 2000.[5]
Modern implementations include:
File managers such as Windows Explorer (since Windows XP) andMidnight Commander utilize natural sorting by default to display file lists.