How to resolve the algorithm Sorting algorithms/Selection sort step by step in the Raku programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sorting algorithms/Selection sort step by step in the Raku programming language
Table of Contents
Problem Statement
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.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Sorting algorithms/Selection sort step by step in the Raku programming language
Source code in the raku programming language
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;
sub selectionSort(@tmp) {
for ^@tmp -> $i {
my $min = $i; @tmp[$i, $_] = @tmp[$_, $i] if @tmp[$min] > @tmp[$_] for $i^..^@tmp;
}
return @tmp;
}
You may also check:How to resolve the algorithm Ackermann function step by step in the Klingphix programming language
You may also check:How to resolve the algorithm Averages/Median step by step in the Rust programming language
You may also check:How to resolve the algorithm Combinations with repetitions step by step in the BASIC programming language
You may also check:How to resolve the algorithm Narcissistic decimal number step by step in the Ksh programming language
You may also check:How to resolve the algorithm Towers of Hanoi step by step in the Seed7 programming language