Sorting in Nim
Our example demonstrates sorting in Nim using the algorithm module. We’ll look at sorting for built-in types.
import algorithm
import strformat
proc main() =
# Sorting functions work for any comparable type.
var strs = @["c", "a", "b"]
strs.sort()
echo fmt"Strings: {strs}"
# An example of sorting integers.
var ints = @[7, 2, 4]
ints.sort()
echo fmt"Ints: {ints}"
# We can also check if a sequence is already in sorted order.
let s = ints.isSorted()
echo fmt"Sorted: {s}"
main()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:
$ nim c -r sorting.nim
Strings: @["a", "b", "c"]
Ints: @[2, 4, 7]
Sorted: trueIn this example:
We import the
algorithmmodule which provides sorting functions, andstrformatfor string interpolation.We define a
mainprocedure to contain our code.We create a sequence of strings and sort it using the
sortprocedure.We do the same with a sequence of integers.
We use the
isSortedfunction to check if a sequence is already sorted.Finally, we call the
mainprocedure 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.