Merge sort


#!/usr/bin/perl -w

# merge two lists, assuming both are sorted in ascending order
sub merge {
  my( $list1ref, $list2ref ) = @_;
  @list1 = @$list1ref;
  @list2 = @$list2ref;
  
  if (!@list1) { return @list2; }
  if (!@list2) { return @list1; }
  
  my( @outlist ) = ();
  foreach (1..(@list1+@list2)) {
    if (!@list1) { push @outlist, shift @list2; }
    elsif (!@list2) { push @outlist, shift @list1; }
    elsif ($list1[0] < $list2[0]) { push @outlist, shift @list1; }
    else { push @outlist, shift @list2; }
  }
  return @outlist;
}

sub mergesort {
  my( @x ) = @_;

  # base case
  if ( @x < 2 ) {return @x;}

  # find midpoint of list x
  my($mid) = int( @x / 2 );

  # split list x evenly into list1 and list2
  my( @list1 ) = (@x)[0..($mid-1)];
  my( @list2 ) = (@x)[$mid..(@x-1)];

  # recursive calls
  @list1 = mergesort( @list1 );
  @list2 = mergesort( @list2 );

  # merge sorted sublists and return
  return merge( \@list1, \@list2 );
}

@testlist = ();
print "Enter elements of list\n";
chomp( $temp = <STDIN> );
while ($temp != 0) {
  push @testlist, $temp;
  chomp( $temp = <STDIN> );
}
print "Input list: @testlist\n";
@msortedlist = mergesort( @testlist );
print "Sorted list: @msortedlist\n";