median

median - #!/usr/bin/perl $n=9; push(@x,int(rand 20)) for...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: #!/usr/bin/perl $n=9; push(@x,int(rand 20)) for (1..$n); #@x=(17,28,26,14,14,28,19,2,0); @s = sort {$a<=>$b} @x; # print "s = " . join(" ",@s) . "\n"; print "."; # for testing with like sh -c 'while true; do perl median.pl; done' $m_sort = $s[$n/2]; # arrays are zero-based $m_find = &find_kth(($n+1)/2,@x); # but k counts from 1 if ($m_sort != $m_find) { print "x = " . join(" ",@x) . "\n"; print "m_sort = $m_sort\n"; print "m_find = $m_find\n"; } sub find_kth { my ($k,@a) = @_; # print "k = $k\n"; # print "a = " . join(" ",@a) . "\n"; my (@l,@g,$ne); # my $p = $a[rand @a]; my $p = $a[0]; # not guaranteed to terminate? # print "p = $p\n"; for my $e (@a) { if ($e < $p) { push(@l,$e) } elsif ($e > $p) { push(@g,$e) } elsif ($e == $p) { ++$ne; } else { die } } # print "l = " . join(" ",@l) . "\n"; # print "g = " . join(" ",@g) . "\n"; if (@l >= $k) { return &find_kth($k,@l) } elsif (@l+$ne >= $k) { return $p } else { return &find_kth($k-@l-$ne,@g) } } ...
View Full Document

Ask a homework question - tutors are online