Skip to content

Commit 1b3dd74

Browse files
committed
Added Perl implementation of Insertion sort
1 parent 069fa94 commit 1b3dd74

2 files changed

Lines changed: 34 additions & 0 deletions

File tree

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package Insertion_Sort;
2+
3+
use strict;
4+
use warnings;
5+
6+
sub insertion_sort {
7+
my $array_ref = shift;
8+
my @array = @$array_ref;
9+
10+
for( my $i = 1; $i <= $#array; $i++ ) {
11+
my $key = $array[ $i ];
12+
my $j = $i - 1;
13+
while( $j >= 0 && $array[ $j ] > $key ) {
14+
$array[ $j + 1 ] = $array[ $j ];
15+
$j--;
16+
}
17+
$array[ $j + 1 ] = $key;
18+
}
19+
20+
return \@array;
21+
}
22+
23+
1;
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
use Test::More;
2+
3+
use Insertion_Sort;
4+
5+
my @array = (5, 4, 3, 2, 1);
6+
7+
is_deeply( Insertion_Sort::insertion_sort( \@array ),
8+
[1, 2, 3, 4, 5],
9+
"Got a sorted array");
10+
11+
done_testing;

0 commit comments

Comments
 (0)