# tst_median.pl - a program to test a function that # computes the median of a given array # median - a function # Parameters: # The number of elements in the second parameter # An array of numbers # Return value: # The median of the array, where median is the # middle element of the sorted array, if the # length is odd; if the length is even, the median # is the average of the two middle elements of the # sorted array use English; sub median { my $len = $_[0]; my @list = @_; # Discard the first element of the array shift(@list); # Sort the parameter array @list = sort @list; # Compute the median if ($len % 2 == 1) { # length is odd return $list[$len / 2]; } else { # length is even return ($list[$len / 2] + $list[$len / 2 - 1]) / 2; } } # End of function median # Begin main program # Create two test arrays @list1 = (1, 3, 5, 2, 4, 6, 8, 0, 9); @list2 = (4, 7, 1, 2, 8, 5, 9, 0); # Call median on both arrays and display the results $med = median(9, @list1); print "The median of the first array is: $med \n"; $med = median(8, @list2); print "The median of the second array is: $med \n";