Skip to content

Instantly share code, notes, and snippets.

@syohex
Created June 28, 2012 08:00
Show Gist options
  • Save syohex/3009790 to your computer and use it in GitHub Desktop.
Save syohex/3009790 to your computer and use it in GitHub Desktop.
merge sort in perl
#!perl
use strict;
use warnings;
sub merge_sort {
my $target_array_ref = shift;
my $len = scalar @{$target_array_ref};
if ($len <= 1) {
return $target_array_ref;
} else {
my ($a_ref, $b_ref) = _split($target_array_ref);
return merge( merge_sort($a_ref), merge_sort($b_ref) );
}
}
sub _split {
my $a_ref = shift;
if (scalar @{$a_ref} == 1) {
return $a_ref;
}
my $num = int(scalar @{$a_ref} / 2);
my @rest = splice @{$a_ref}, $num;
return ($a_ref, \@rest);
}
sub merge {
my ($a_ref, $b_ref) = @_;
my ($a_len, $b_len) = map { scalar @{$_} } ($a_ref, $b_ref);
if ($a_len == 0) {
return $b_ref;
} elsif ($b_len == 0) {
return $a_ref;
} else {
my ($a, $b) = ($a_ref->[0], $b_ref->[0]);
if ($a <= $b) {
shift @{$a_ref};
my $c_ref = merge($a_ref, $b_ref);
unshift @{$c_ref}, $a;
return $c_ref;
} else {
shift @{$b_ref};
my $c_ref = merge($a_ref, $b_ref);
unshift @{$c_ref}, $b;
return $c_ref;
}
}
}
my @a;
map { push @a, int(rand(10)) } 1..5;
print "Before sort: [ @a ]\n";
my @sorted = @{ merge_sort(\@a) };
print "After sort: [ @sorted ]\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment