Hacker News new | ask | show | jobs
by ncruces 51 days ago
> "median of medians" (finding the median in a list in O(n) worst-case time) is useless because it is not used in practice.

This one is just not true. Here it is in 255 lines of well commented Go code: https://github.com/ncruces/sort/blob/v1.0.3/quick/quick.go

It's worse case linear, as used for sorting it beats the Go standard library on the average and worst cases, lagging a bit on the best cases.

In my experience, median-on-ninthers (which is only slightly more complicated than median-of-medians) definitely beats both heap sort and particularly heap select as a fall back for the degenerate case.

And it's not just academic: I've sped up significant stuff at work by switching from sorting to partial sorting and/or selection.

1 comments

That's not median-of-medians, that's quickselect. Quickselect is useful and practical yes. Theoreticians don't like it because of the randomization (or non-worst-caseness)
> In computer science, the median of medians is an approximate median selection algorithm, frequently used to supply a good pivot for an exact selection algorithm, most commonly quickselect…

https://en.wikipedia.org/wiki/Median_of_medians

That's pretty much what I posted: median-of-ninthers is an evolution of median-of-medians, that I use to pick a better pivot whenever the pivot supplied by median-of-3 turns out to be bad.

Using it all the time would simply make quicksort/quickselect about twice as slow as it is now, but still faster than heapsort/heapselect. It's a better backstop algorithm than the common introsort/introselect.

There's also no randomisation, the implementation is completely deterministic, and depends exclusively on the input order.

And median-of-ninthers is faster, but median-of-medians is far from terrible, so calling it a galactic algorithm or completely useless in practice is far from the truth, IMO.