in reply to Puzzle: The Ham Cheese Sandwich cut.
As ambrus said, even the warm-up problem is pretty damned hard. I too cheated by looking in Cormen, Leiserson and Rivest. Here is a Perl implementation of the linear-time algorithm they give.
In practice it's pretty inefficient, and even proving that it runs in linear time is not entirely trivial!sub naive_median { (sort {$a <=> $b} @_)[@_/2]; } sub nth_largest { my ($n, @a) = @_; die "You can't find the ${n}th-largest element of an ".@a."-element +array!" if $n > $#a || $n < 0; #warn "Looking for ${n}th element of (@a)\n"; return $a[0] if $n == 0; my @medians; for(my $i=0; $i < @a; $i += 5) { push @medians, naive_median(@a[$i..($i+4 > $#a ? $#a : $i+4)]); } my $median = median(@medians); my @smaller = grep {$_ < $median} @a; return nth_largest($n, @smaller) if $n < @smaller; my @larger = grep {$_ >= $median} @a; return nth_largest($n - @smaller, @larger); } sub median { unshift @_, int(@_/2); goto &nth_largest; }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Puzzle: The Ham Cheese Sandwich cut.
by Roy Johnson (Monsignor) on Nov 21, 2005 at 19:17 UTC | |
by robin (Chaplain) on Nov 21, 2005 at 19:28 UTC | |
by Roy Johnson (Monsignor) on Nov 21, 2005 at 19:31 UTC | |
by robin (Chaplain) on Nov 21, 2005 at 19:39 UTC | |
Re^2: Puzzle: The Ham Cheese Sandwich cut.
by hv (Prior) on Nov 22, 2005 at 13:19 UTC | |
by Perl Mouse (Chaplain) on Nov 22, 2005 at 14:05 UTC |
In Section
Meditations