Natural Order String Comparison

by Martin Pool

This project has moved to

Computer string sorting algorithms generally don't order strings containing numbers in the same way that a human would do. Consider:


It would be more friendly if the program listed the files as


Filenames sort properly if people insert leading zeros, but they don't always do that.

I've written a subroutine that compares strings according to this natural ordering. You can use this routine in your own software, or download a patch to add it to your favourite Unix program.


Strings are sorted as usual, except that decimal integer substrings are compared on their numeric value. For example,


Strings can contain several number parts:

in which case numeric fields are separated by nonnumeric characters. Leading spaces are ignored. This works very well for IP addresses from log files, for example.

Leading zeros are not ignored, which tends to give more reasonable results on decimal fractions.

1.001 < 1.002 < 1.010 < 1.02 < 1.1 < 1.3

Some applications may wish to change this by modifying the test that calls isspace.


Longer example of the results


This software is copyright by Martin Pool, and made available under the same licence as zlib:






This licence applies only to the C implementation. You are free to reimplement the idea fom scratch in any language.

Related Work



The PHP scripting language now has a strnatcmp function based on this code. The PHP wrapper was done by Andrei Zimievsky.

Stuart Cheshire has a Macintosh system extension to do natural ordering. I indepdendently reinvented the algorithm, but Stuart had it first. I borrowed the term natural sort from him.

Sort::Versions in Perl. "The code has some special magic to deal with common conventions in program version numbers, like the difference between 'decimal' versions (eg perl 5.005) and the Unix kind (eg perl 5.6.1)."

Sort::Naturally is also in Perl, by Sean M. Burke. It uses locale-sensitive character classes to sort words and numeric substrings in a way similar to natsort.

Ed Avis wrote something similar in Haskell.

Pierre-Luc Paour wrote a NaturalOrderComparator in Java

Kristof Coomans wrote a natural sort comparison in Javascript

Alan Davies wrote natcmp.rb, an implementation in Ruby.

Numacomp - similar thing in Python.

as3natcompare implementation in Flash ActionScript 3.

Get It!

To Do

Comparison of characters is purely numeric, without taking character set or locale into account. So it is only correct for ASCII. This should probably be a separate function because doing the comparisons will probably introduce a dependency on the OS mechanism for finding the locale and comparing characters.

It might be good to support multibyte character sets too.

If you fix either of these, please mail me. They should not be very hard.