Skip to main content

natural_sort

Function natural_sort 

Source
pub fn natural_sort(a: &str, b: &str) -> Ordering
Expand description

Performs natural sorting comparison between two strings.

Natural sorting is an ordering that handles numeric sequences in a way that matches human expectations. For example, “file2” comes before “file10” (unlike standard lexicographic sorting).

§Characteristics

  • Case-sensitive with lowercase priority: When comparing same letters, lowercase comes before uppercase
  • Numbers are compared by numeric value, not character by character
  • Leading zeros affect ordering when numeric values are equal
  • Can handle numbers larger than u128::MAX (falls back to string comparison)
  • When strings are equal case-insensitively, lowercase is prioritized (lowercase < uppercase)

§Algorithm

The function works by:

  1. Processing strings character by character in a case-insensitive manner
  2. When encountering digits, treating consecutive digits as a single number
  3. Comparing numbers by their numeric value rather than lexicographically
  4. For non-numeric characters, using case-insensitive comparison
  5. If everything is equal case-insensitively, using case-sensitive comparison as final tie-breaker