Sorting in Nim
Our example demonstrates sorting in Nim using the algorithm
module. We’ll look at sorting for built-in types.
Sorting functions in Nim are generic and work for any comparable type. The algorithm
module provides sorting functionality for sequences.
To run the program, save it as sorting.nim
and use the Nim compiler:
In this example:
We import the
algorithm
module which provides sorting functions, andstrformat
for string interpolation.We define a
main
procedure to contain our code.We create a sequence of strings and sort it using the
sort
procedure.We do the same with a sequence of integers.
We use the
isSorted
function to check if a sequence is already sorted.Finally, we call the
main
procedure to execute our code.
Nim’s sorting functions modify the original sequence in-place, unlike some languages which return a new sorted sequence. The @
symbol is used to create a sequence literal in Nim.
This example demonstrates how Nim provides simple and efficient sorting capabilities for built-in types.