user
Task

Sort an array (or list) of elements using the Selection sort algorithm.

It works as follows:

First find the smallest element in the array and exchange it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and continue in this way until the entire array is sorted.

Its asymptotic complexity is    O(n2)    making it inefficient on large arrays.

Its primary purpose is for when writing data is very expensive (slow) when compared to reading, eg. writing to flash memory or EEPROM.

No other sorting algorithm has less data movement.

References

* Rosetta Code:   O     (complexity).
* Wikipedia:   Selection sort.
* Wikipedia:   [Big O notation].
assistant
(formerly Perl 6)
Solution 1:

```
sub selection_sort ( @a is copy ) {
    for 0 ..^ @a.end -> $i {
        my $min = [ $i+1 .. @a.end ].min: { @a[$_] };
        @a[$i, $min] = @a[$min, $i] if @a[$i] > @a[$min];
    }
    return @a;
}

my @data = 22, 7, 2, -5, 8, 4;
say 'input  = ' ~ @data;
say 'output = ' ~ @data.&selection_sort;

```

Output:

```
input  = 22 7 2 -5 8 4
output = -5 2 4 7 8 22

```

Solution 2:

```
sub selectionSort(@tmp) {
    for ^@tmp -> $i {
        my $min = $i; @tmp[$i, $_] = @tmp[$_, $i] if @tmp[$min] > @tmp[$_] for $i^..^@tmp;
    }
    return @tmp;
}

```

Output:

```
input  = 22 7 2 -5 8 4
output = -5 2 4 7 8 22

```