Sorting algorithms/Insertion sort: Difference between revisions

Content added Content deleted
(→‎{{header|C}}: Keep indexing the same as the shell sort)
(→‎{{header|Perl}}: an insertion sort should become O(n) when already sorted so the splice method from before wouldnt be good.)
Line 839: Line 839:
<lang perl>
<lang perl>
sub insertion_sort {
sub insertion_sort {
my @a = @_;
my (@a, $i, $j, $k) = @_;
for my $i (0 .. $#a) {
for ($i = 1; $i < @a; $i++) {
for my $j (0 .. $i - 1) {
$k = $a[$i];
if ($a[$i] < $a[$j]) {
for ($j = $i - 1; $j >= 0 && $k < $a[$j]; $j--) {
my $k = splice @a, $i, 1;
$a[$j + 1] = $a[$j];
splice @a, $j, 0, $k;
last;
}
}
}
$a[$j + 1] = $k;
}
}
@a;
@a;
}
}



my @a = (4, 65, 2, -31, 0, 99, 83, 782, 1);
my @a = (4, 65, 2, -31, 0, 99, 83, 782, 1);