Improve documentation of slice::sort_by_key and slice::sort_unstable_by_key #71132
Labels
C-enhancement
Category: An issue proposing an enhancement or a PR with one.
T-libs-api
Relevant to the library API team, which will review and decide on the PR/issue.
The current documentation for
slice::sort_by_key
andslice::sort_unstable_by_key
method claims that for a slice ofn
elements, the method takesO(m n log(m n))
worst-case, where the key function isO(m)
.rust/src/liballoc/slice.rs
Lines 257 to 258 in d28a464
Although this is not wrong, this time complexity is not tight and can be replaced with
O(m n log n)
as far as my understanding.Brief explanation relying on another doc claiming the time complexity of
merge_sort
, whichslice::sort_by_key
relies on, isO(n log n)
worst-case;Since its running time is
O(n log n)
,merge_sort
can callis_less
onlyO(n log n)
times. Each call ofis_less
makes2
calls of the key function, so the total time complexity taken by the key function isO((2 n log n) * m) = O(m n log n)
.Because other part of
merge_sort
takesO(n log n)
as the doc states, its total running time isO(n log n + m n log n) = O(m n log n)
.Exact same discussion applies to
sort_unstable_by_key
+sort::quicksort
.The text was updated successfully, but these errors were encountered: