5 ms·
> uses fixed space I guess the "normal" way to write this is with a heap? For `min`, I guess the algorithm is something like, min(items, k=1): h = max_h
by repsilat 12y ago
> uses fixed space
I guess the "normal" way to write this is with a heap? For `min`, I guess the algorithm is something like,
min(items, k=1):
h = max_heap(items[:k])
for i in items[k:]:
h.push(i)
h.pop_max()
return sorted(h)
It isn't asymptotically slower than the normal algorithm for k=1, it doesn't need to make multiple passes over the data, and it doesn't mutate the original data structure, so it's a pretty sensible and natural extension to put in.
- riffraff 12y agoyes, it's not hard (although I seem to recall mysql only implemented "limit" like this in v5.6), it's just that if it's not readily available people (well, me) tend to fall back to sort+first(n), which can be quite wasteful.