Created
August 30, 2017 01:14
-
-
Save haodemon/bd72a7fc94798ee624e82afab24d7dbf to your computer and use it in GitHub Desktop.
Do not use in prod. Augmented due to boredom on an airplane - ran out of books to read and wanted to scare a nice fellow sitting to the right of me. Hey!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use 5.016; | |
use strict; | |
use warnings; | |
sub array_to_string($) { | |
'[' . join(', ', @{$_[0]}) . '];'; | |
} | |
# array, first_index, second_index; (a, b) = (b, a); | |
sub swap($$$) { | |
($_[0]->[$_[1]], $_[0]->[$_[2]]) = ($_[0]->[$_[2]], $_[0]->[$_[1]]); # LOL | |
} | |
# array, startIndex; | |
sub index_of_min($$) { | |
my $min_index = $_[1]; | |
my $min_value = $_[0]->[$min_index]; | |
for (my $i = $_[1] + 1; $i < scalar(@{$_[0]}); $i++) { | |
if ($min_value > $_[0]->[$i]) { | |
$min_value = $_[0]->[$i]; | |
$min_index = $i; | |
}; | |
} | |
return $min_index; | |
} | |
sub selection_sort($) { | |
for (my $i = 0; $i < scalar(@{$_[0]}); $i++) { | |
swap $_[0], $i, index_of_min $_[0], $i; | |
} | |
} | |
my $array = [1, 2, 3, 0, 2, 3]; | |
say "before: " . array_to_string $array; | |
selection_sort $array; | |
say "after: " . array_to_string $array; # [0, 1, 2, 2, 3, 3]; | |
say "-------"; | |
$array = [22, 11, 99, 88, 9, 7, 42]; | |
say "before: " . array_to_string $array; | |
selection_sort $array; | |
say "after: " . array_to_string $array; # [7, 9, 11, 22, 42, 88, 99] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment