The warm-up problem isn't so trivial. Two possible solutions are decribed in Cormen – Leiserson – Rivest – Stein: Introduction to Algorithms. One of these is randomized and runs in expected O(n) time. (Update: the other one runs in guaranteed O(n) time, as Perl Mouse has noted in his reply. I'm sorry this wasn't clear from my original post.)

I've recently implemented this randomized algorithm for perl, although my implementation is not a very efficent one, as it would be possible to do all its operations in place (with only O(n) extra memory and more importantly less time).

The rest of this post shows my implementation.

Here's the code although it might not make much sense without context. The quantile function is passed a positive ordinal $r and a list of numbers @a. It returns the $r-th least number from the list if it would be sorted, with $r = 1 meaning to return the minimum of the list. If you want a median, pass $r = int((@a + 1)/2)

sub quantile { my($n, @a) = @_; my($q); @a < $n and return 9e9999; $q = quantile1($n, @a); if (1) { # DEBUG check postcondition my($nl, $nle); $nl = grep { $_ < $q } @a; $nle = grep { $_ <= $q } @a; $nl < $n && $n <= $nle or die "postcondition failed"; } $q; } sub quantile1 { my($n, @a) = @_; my($c, $v, @l, @h); @a <= 1 and do { @a or die "internal error: quantile1 called on empty + list, n=" . $n; return $a[0]; }; $c = @a[rand(@a)]; for $v (@a) { if ($v < $c) { push(@l, $v); } elsif ($c < $v) { push(@h, $v); } } if ($n <= @l) { quantile1($n, @l); } elsif ($n > @a - @h) { quantile1($n - @a + @h, @h); } else { $c; } }

In reply to Re: Puzzle: The Ham Cheese Sandwich cut. by ambrus
in thread Puzzle: The Ham Cheese Sandwich cut. by Perl Mouse

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.