function that returns the middle of an array
tcf03
created: 2006-01-10 08:35:15
This function returns the middle of a array sorted array
sub Return_Middle
{
    my @list = @_;
    return @list if ( scalar(@list) == 2 or
                      scalar(@list) == 1 );
    my @sorted = sort { $a <=> $b || $a cmp $b } @list;
    my @middle = drill_down(@sorted);
    return @middle;
      

   sub drill_down
   {
       my @list = @_;
       return @list if ( scalar(@list) == 2 );
       return @list if ( scalar(@list) == 1 );
       splice @list, -1, 1;
       splice @list, 0, 1;
       drill_down(@list);
   }
}
Re: function that returns the middle of an array
created: 2006-01-10 09:26:44

How 'bout

sub drill_down {
    my $i=@_/2;
    @_[ @_%2 ? $i : ($i-1, $i) ];
}

instead?

Also, in various order:

  • No need for those [doc://scalar]s as == will impose scalar context anyway,
  • You may just do:
    drill_down(@sorted);  # as the last statement in your sub
    
    instead of
    my @middle = drill_down(@sorted);
    return @middle;
    
  • While it is perfectly legal to define the drill_down sub inside the Return_Middle one, they will be "global" anyway, and to do so would have some sense only if the former were a closure around some variable(s) lexically scoped to the latter, which is not the case.
Re: function that returns the middle of an array
created: 2006-01-10 10:57:59
How about this? You find the middle of the array, which will either be an integer or a half-value. Return the slice indexed from the integer portion of the midpoint through the integer portion of the midpoint + .5. If the midpoint is a half-value, those will be different (so you return the two values that straddle the middle); otherwise, they will be the same, and you return just one value.
sub Return_Middle {
  my $midpt = ($#_/2);
  @_[int($midpt) .. int($midpt + .5)];
}

Caution: Contents may have been coded under pressure.
Re^2: function that returns the middle of an array
created: 2006-01-10 12:30:05

I think that your subroutine doesn't sort the array so it just returns the elements at the middle, not the median of the array.

Re: function that returns the middle of an array
created: 2006-01-10 12:36:10

See also Re: Puzzle: The Ham Cheese Sandwich cut. (by robin) and Re: Puzzle: The Ham Cheese Sandwich cut. (by me) for a different way to find the median.

perlmonks.org content © perlmonks.org and ambrus, blazar, Roy Johnson, tcf03

prlmnks.org © 2006 edmund von der burg (eccles & toad)

v 0.03