Sorting in Crystal
Crystal provides built-in sorting capabilities for arrays and other collections. Let’s look at sorting for built-in types.
Crystal’s standard library provides sorting capabilities for built-in types. The sort!
method is used to sort arrays in-place, modifying the original array.
Sorting functions in Crystal work for any comparable type. For strings and numbers, the default comparison is used, which sorts strings lexicographically and numbers in ascending order.
The sorted?
method can be used to check if an array is already in sorted order.
To run the program, save it to a file (e.g., sorting.cr
) and use the crystal
command:
Crystal’s sorting functionality is part of the standard library and doesn’t require importing additional modules, unlike some other languages. The sorting is performed efficiently and is stable (meaning that equal elements retain their relative order).