Created
January 5, 2015 08:34
-
-
Save chankeypathak/3f2e0ab9b0d26c912be4 to your computer and use it in GitHub Desktop.
Merge Sort in Perl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use strict; | |
use warnings; | |
sub merge { | |
my($s, @b) = @_; | |
my(@a) = splice(@b, $s); | |
if (@a * @b == 0) { return @a, @b; } | |
my($head) = $a[0] < $b[0] ? shift(@a) : shift(@b); | |
return $head, merge(int(@a), @a, @b); | |
} | |
sub mergesort { | |
my($half) = int(@_ / 2); | |
if ($half == 0) { return @_; } | |
return merge($half, mergesort(splice(@_, $half)), mergesort(@_)); | |
} | |
my(@sorted) = mergesort(10, 9, 8, 4, 5, 6, 7, 3, 2, 1); | |
print(join(" ", @sorted) . "\n"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Demo: http://ideone.com/MOnCoB