Add Enumerable#min(count) and #max(count)#13057
Add Enumerable#min(count) and #max(count)#13057straight-shoota merged 5 commits intocrystal-lang:masterfrom
Enumerable#min(count) and #max(count)#13057Conversation
There was a problem hiding this comment.
Thanks @nthiad for this work! @HertzDevil already gave a thorough review; I'm just adding two little grammar fixes.
EDIT: probably they're ok, deleting my comments.
… and prevent source array modification (crystal-lang#12817)
|
Passing negative |
|
@Sija Agreed. See #12817 (comment) |
There was a problem hiding this comment.
It would be great to have the full name of the algorithm show up somewhere to make it findable.
Either mentioning that in a comment on the helper method or renaming it to quickselect_internal - both should work. But I don't think there's a compelling reason to abbreviate the method name, so I'd prefer spelling it out.
…erval, qselect => quickselect, error message, formatting (crystal-lang#12817)
straight-shoota
left a comment
There was a problem hiding this comment.
LGTM 👍
As possible future enhancements, the algorithm could use more efficient mechanics such as wrapping operators (&+) as well as unsafe_fetch and Pointer#swap to skip bounds checking. These operations should be guaranteed to be safe in this context.
Enumerable#min(count) and #max(count)
Thanks @Sija Co-authored-by: Sijawusz Pur Rahnama <sija@sija.pl>
beta-ziliani
left a comment
There was a problem hiding this comment.
I took the liberty to directly commit Sija's observations. @nthiad if you disagree with these let us know, we can always roll it back.
This patch adds
max(k),min(k),max?(k), andmin?(k)support as requested in #12817.Like ruby core, this patch uses an internal quickselect implementation which empirically has much better performance than full sorting when
kis small. However, whenkis large, the performance is also poor, but that is also the case in ruby core.Here is a little benchmark script comparing
max(k)withsort():It runs but hangs for quite a while on the last
max(k):but that is exactly what ruby does:
It might be worth pointing out these performance characteristics in the docs, but ruby doesn't do that so I decided not to in this patch.
I tried to preserve the other quirks from the ruby implementation such as
k > array.sizetruncating results instead of raising an exception. And raising an exception whenk < 0.