SultanC
  1. Home
  2. Examples
  3. Algorithms

Insertion sort in place through a mutable reference

algorithms/insertion_sort.sn
// Insertion sort in place through a mutable reference.
import std.io.println;
import std.text.number;
import std.text.transform;

def insertion_sort(values: &mutable vector int): void {
    let i: mutable uint = 1;
    while (i < (length(*values) as uint)) {
        let current: int = (*values)[i];
        let j: mutable uint = i;
        while (j > 0 && (*values)[j - 1] > current) {
            (*values)[j] := (*values)[j - 1];
            j := j - 1;
        }
        (*values)[j] := current;
        i := i + 1;
    }
}

def main(): int {
    let values: mutable vector int = [31, 4, 15, 9, 26, 5, 3];
    insertion_sort(&mutable values);
    let texts: mutable vector string = [];
    let i: mutable uint = 0;
    while (i < (length(values) as uint)) {
        append(texts, int_to_text(values[i]));
        i := i + 1;
    }
    let space: string = " ";
    println(join(&texts, &space));
    return 0;
}

Run it

With the interpreter, without compiling:

./build/sultanc run examples/en/algorithms/insertion_sort.sn

Or compile it to an executable:

./build/sultanc examples/en/algorithms/insertion_sort.sn -o build/example && ./build/example

Source on GitHub   All examples