34 / Advanced

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.

34-sorting.nxSource →
// 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)
}

// El mismo recorrido para arrays de String: el tipo del elemento se declara
// al leerlo (`let v: String`), porque un Array no lo lleva consigo: anotar
// `int` acá imprimiría la dirección de cada string en vez del texto.
fn print_array_str(arr: Array) {
    var s: String = "["
    var i: int = 0
    while i < arr.length() {
        let v: String = arr[i]
        s = s + 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_str(palabras)

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

    return 0
}
Outputstdout
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]

How it works

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 helpers print_array and print_array_str demonstrate manual array traversal with a while loop and an index variable — the standard Nyx pattern when you need index-based access rather than an iterator pipeline. There are two of them because an Array does not carry the type of its elements: the traversal declares it when reading, and reading a string array as int would print the address of each string instead of its text.