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 includes sorting functionality
# for arrays and other collections

# Sorting strings
strs = ["c", "a", "b"]
strs.sort!
puts "Strings: #{strs}"

# An example of sorting integers
ints = [7, 2, 4]
ints.sort!
puts "Ints:    #{ints}"

# We can also check if an array is already in sorted order
s = ints.sorted?
puts "Sorted:  #{s}"

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 sorting.cr
Strings: ["a", "b", "c"]
Ints:    [2, 4, 7]
Sorted:  true

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).