CGI Find the Median Value of an Array

Find the Median Value of an Array

# median() returns a median value.
# USAGE: median(@array) where @array is
# an array of all values
# to be considered.
#
sub median {
my(@values) = sort(@_);
my($mid) = scalar(@values) >> 1;

# If there is an even number of values
# in @values, then you need to add them
# and divide by two to get the median.

return($values[$mid]) if $mid & 1;

($values[$mid-.5] + $values[$mid+.5]) / 2;
}