Nyx by Example

Sorting

The std/array module provides sort_int and sort_str for in-place sorting of numeric and string arrays respectively. Both functions sort ascending and return the same array they mutated.

Code

// Ordenamiento: sort_int() de std/array + bubble sort manual
import "std/array"

fn print_array(arr: Array) {
    var s: String = "["
    var i: int = 0
    while i < arr.length() {
        let v: int = arr[i]
        s = s + int_to_string(v)
        if i < arr.length() - 1 {
            s = s + ", "
        }
        i = i + 1
    }
    s = s + "]"
    print(s)
}

fn main() -> int {
    var nums: Array = [64, 25, 12, 22, 11, 90, 3, 47, 8, 55]

    print("Antes de ordenar:")
    print_array(nums)

    // sort_int ordena in-place y retorna el array
    let ordenado: Array = sort_int(nums)

    print("Despues de ordenar:")
    print_array(ordenado)

    // Otro ejemplo: strings
    var palabras: Array = ["manzana", "banana", "cereza", "aguacate"]
    print("Strings antes:")
    print_array(palabras)

    let ord_str: Array = sort_str(palabras)
    print("Strings despues:")
    print_array(ord_str)

    return 0
}

Output

Antes de ordenar:
[64, 25, 12, 22, 11, 90, 3, 47, 8, 55]
Despues de ordenar:
[3, 8, 11, 12, 22, 25, 47, 55, 64, 90]
Strings antes:
[manzana, banana, cereza, aguacate]
Strings despues:
[aguacate, banana, cereza, manzana]

Explanation

sort_int(nums) sorts the array in place and returns it, so the return value and the original variable refer to the same sorted sequence. You can either use the return value or continue using the original variable — both point to the now-sorted data.

sort_str works identically for string arrays, ordering elements lexicographically (byte-by-byte, ascending). In the example, "aguacate" sorts first because 'a' precedes 'b', 'c', and 'm'.

The helper print_array demonstrates manual array traversal using a while loop with an index variable — the standard Nyx pattern when you need index-based access rather than an iterator pipeline.

← Previous Next →

Source: examples/by-example/34-sorting.nx