summaryrefslogtreecommitdiff
path: root/docs/chapter25/examples/BubbleSort.smp
blob: ca6906b5d2f0d5348ec553ef5d7cf1a929318ab0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

// An implementation of
// https://sampleprograms.io/projects/bubble-sort/
//
// Bubble sort, with reading (parsing) and writing (formatting) the data.

val sort = { !sys.aryi64 nums ->
    sys.aryi64?! more = nums;
    while( more ) {
        more = null;
        for( var i = 0; i < nums.len-1; i++ )
            if( nums.buf[i] > nums.buf[i+1] )
                more = nums.swap(i,i+1);
    }
};

// Read one process argument of the form "[ 4, 3, 2, 1]" and print it sorted.
// args[0] is the executable name, as with native C argc/argv.
val main = { u8[~][] args ->
    val usage = { ->
        sys.io.p("Usage: please provide a list of at least two integers to sort in the format \"[1, 2, 3, 4, 5]\"\n");
        return 0;
    };
    if( args# != 2 ) return usage();

    var nums = sys.aryi64.parseAryI64(args[1]);
    if( !nums ) return usage();
    if( nums.len < 2 ) return usage();

    // Bubble sort array of integers
    sort(nums);

    // Print the same bracketed array-list format accepted as input.
    nums.str().add('\n').write(1);
    return 0;
};