insertion sort


See On Github

Data

Contributor

Generic placeholder thumbnail

by Sweet-kid

in perl

Source Code

package Insertion_Sort;

use strict;
use warnings;

sub insertion_sort {
    my $array_ref = shift;
    my @array = @$array_ref;

    for( my $i = 1; $i <= $#array; $i++ ) {
        my $key = $array[ $i ];
        my $j = $i - 1;
        while( $j >= 0  && $array[ $j ] > $key ) {
            $array[ $j + 1 ] = $array[ $j ];
            $j--;
        }
        $array[ $j + 1 ] = $key;
    }

    return \@array;
}

1;
use Test::More;

use Insertion_Sort;

my @array = (5, 4, 3, 2, 1);

is_deeply( Insertion_Sort::insertion_sort( \@array ),
           [1, 2, 3, 4, 5],
	   "Got a sorted array");

done_testing;