Loading…

Natural Sort Comparator

Plain string comparison treats every character as just a character, including digits, so "Report10" sorts before "Report2" - the character '1' is less than '2', even though ten is obviously the bigger number. This shows up constantly in any list a person actually has to read: exported report filenames, numbered symbol labels, magic-number-tagged strategy names, log filenames with a running index. This header compares digit runs numerically instead of character by character. Numbers of any length are handled safely by comparing digit-run length first, then the digits themselves once leading zeros are stripped - not by parsing into an int, which would overflow or misbehave on an unusually long numeric run. Everything that isn't a digit run compares case-insensitively, matching how most file managers already sort names. Two runs that are numerically equal but padded differently ("007" and "7") compare as equal, as a person would expect. Notes and limitations NaturalSortArray uses an insertion sort, O(n^2) worst case - deliberately fine for the sizes this header targets (symbol lists, filename lists: dozens to low hundreds of entries), not intended for sorting bulk data. The comparison only recognises the ASCII digits 0-9 and ASCII letters for case-folding; it has no locale awareness and does not handle Unicode digit variants or accented-letter case-folding. A string containing a digit run longer than any practical filename or label still compares correctly (length-then-lexical comparison never overflows, unlike parsing into an integer would), but extremely long inputs will naturally run slower since the comparison is still ultimately character-by-character.

Script · MT4 · v1.0 · Free

About Natural Sort Comparator

Natural Sort Comparator is a script for MetaTrader 4. MQL source code included.

Files in the download: NaturalSortComparator.mqh, NaturalSortComparator.txt, NaturalSortComparatorDemo.mq4.

How to install

  1. Download the ZIP from your PolyMaria library and unzip it.
  2. In MetaTrader 4 open File → Open Data Folder, then go to MQL4 → Scripts.
  3. Copy the .mq4 file(s) there. Put any .mqh files in MQL4 → Include.
  4. Open the .mq4 file in MetaEditor and press Compile (F7) if MetaTrader does not show it.
  5. Drag the script onto a chart to run it once.

Download the PDF guide

Tags: MT4 Script · MQL4 Source Code

MQL4 & MQL5 scripts · PolyMaria