rust/library/core/src/slice
Matthias Krüger 788671c1c6
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.
2023-01-18 06:59:22 +01:00
..
iter replace manual ptr arithmetic with ptr_sub 2023-01-15 17:38:05 +01:00
ascii.rs EscapeAscii is not an ExactSizeIterator 2022-07-29 00:35:38 +00:00
cmp.rs make memcmp return a value of c_int_width instead of i32 2022-04-02 17:21:08 -07:00
index.rs Adjust inlining attributes around panic_immediate_abort 2022-11-29 09:24:01 -05:00
iter.rs replace manual ptr arithmetic with ptr_sub 2023-01-15 17:38:05 +01:00
memchr.rs Rollup merge of #100823 - WaffleLapkin:less_offsets, r=scottmcm 2022-09-24 14:29:52 +02:00
mod.rs Rollup merge of #106889 - scottmcm:windows-mut, r=cuviper 2023-01-17 20:21:27 +01:00
raw.rs Print the precondition we violated, and visible through output capture 2022-10-26 22:09:17 -04:00
rotate.rs Make ZST checks in core/alloc more readable 2022-09-22 23:12:29 -07:00
sort.rs Add heapsort fallback in select_nth_unstable 2023-01-17 19:38:37 +01:00
specialize.rs Remove size_of == 1 case from fill specialization. 2021-08-09 19:25:28 +02:00