]> git.lizzy.rs Git - rust.git/commit
Rollup merge of #106997 - Sp00ph:introselect, r=scottmcm
authorMatthias Krüger <matthias.krueger@famsik.de>
Wed, 18 Jan 2023 05:59:22 +0000 (06:59 +0100)
committerGitHub <noreply@github.com>
Wed, 18 Jan 2023 05:59:22 +0000 (06:59 +0100)
commit788671c1c62e099b2ad4ff5384c6f764b8b26b8d
tree7693b9d1990c1a9bf003a05bec813d96bd5de4a8
parentf547bb57155470ce57fec9a7b7aec6927468c4bb
parent273c6c3913e4d32c3321a3c92fb2ce32c1db9cb8
Rollup merge of #106997 - Sp00ph:introselect, r=scottmcm

Add heapsort fallback in `select_nth_unstable`

Addresses #102451 and #106933.

`slice::select_nth_unstable` uses a quick select implementation based on the same pattern defeating quicksort algorithm that `slice::sort_unstable` uses. `slice::sort_unstable` uses a recursion limit and falls back to heapsort if there were too many bad pivot choices, to ensure O(n log n) worst case running time (known as introsort). However, `slice::select_nth_unstable` does not have such a fallback strategy, which leads to it having a worst case running time of O(n²) instead. #102451 links to a playground which generates pathological inputs that show this quadratic behavior. On my machine, a randomly generated slice of length `1 << 19` takes ~200µs to calculate its median, whereas a pathological input of the same length takes over 2.5s. This PR adds an iteration limit to `select_nth_unstable`, falling back to heapsort, which ensures an O(n log n) worst case running time (introselect). With this change, there was no noticable slowdown for the random input, but the same pathological input now takes only ~1.2ms. In the future it might be worth implementing something like Median of Medians or Fast Deterministic Selection instead, which guarantee O(n) running time for all possible inputs. I've left this as a `FIXME` for now and only implemented the heapsort fallback to minimize the needed code changes.

I still think we should clarify in the `select_nth_unstable` docs that the worst case running time isn't currently O(n) (the original reason that #102451 was opened), but I think it's a lot better to be able to guarantee O(n log n) instead of O(n²) for the worst case.