Sorting
Selection Sort
Repeatedly find the index of the smallest remaining element and swap it into the next "sorted prefix" slot. Unlike bubble sort, only one swap per pass.
Algorithm
Canonical input (5, 1, 4, 2, 8) finishes after four passes, with
two real swaps (passes 0 and 1) and two skip-swap passes
($min_idx == $i). Final array [1, 2, 4, 5, 8].
Basic Implementation
basic.pl
use strict; use warnings;
my @arr = (5, 1, 4, 2, 8);
my $n = scalar @arr;
my $i = 0;
while ($i < $n - 1) {
my $min_idx = $i;
my $j = $i + 1;
while ($j < $n) {
if ($arr[$j] < $arr[$min_idx]) {
$min_idx = $j;
}
$j = $j + 1;
}
if ($min_idx != $i) {
my $tmp = $arr[$i];
$arr[$i] = $arr[$min_idx];
$arr[$min_idx] = $tmp;
}
$i = $i + 1;
}
print "[" . join(", ", @arr) . "]\n";
Complexity
- Time: O(n^2) regardless of input order
- Space: O(1)
- Stable: no
- Swap count: at most n-1
Implementation notes
- Perl: same loop shape as Python / Java / JavaScript / C++ / C / Go /
Rust / C# / Kotlin / Swift / Scala / Ruby / PHP. The
if ($min_idx != $i)guard is the canonical skip-swap variant from the lesson spec. my $min_idx = $i;keeps the running-minimum invariant visible; the three-linemy $tmp = $arr[$i]; $arr[$i] = $arr[$min_idx]; $arr[$min_idx] = $tmp;swap mirrors the bubble-sort lesson rather than collapsing into list-slice assignment.- The replay highlights the current
$min_idxdistinctly from the scanning index$jso the viewer sees the running minimum travel.
running minimum
`$min_idx` tracks the index of the smallest value seen in `@arr[$i..$#arr]`.
sorted prefix
After each pass, `@arr[0..$i]` is the final sorted prefix.