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:  true

In this example:

  1. We import the algorithm module which provides sorting functions, and strformat for string interpolation.

  2. We define a main procedure to contain our code.

  3. We create a sequence of strings and sort it using the sort procedure.

  4. We do the same with a sequence of integers.

  5. We use the isSorted function to check if a sequence is already sorted.

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