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 |
for ($i = 1; $i < @a; $i++) { |
||
$k = $a[$i]; |
|||
for ($j = $i - 1; $j >= 0 && $k < $a[$j]; $j--) { |
|||
$a[$j + 1] = $a[$j]; |
|||
splice @a, $j, 0, $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); |