Skip to content

Commit b8452cc

Browse files
committed
Clarify behaviour of sort_unstable_by_key with respect to sort_by_key
1 parent 670e69e commit b8452cc

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

src/liballoc/slice.rs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1303,6 +1303,7 @@ impl<T> [T] {
13031303
/// Sorts the slice with a key extraction function.
13041304
///
13051305
/// During sorting, the key function is called only once per element.
1306+
///
13061307
/// This sort is stable (i.e. does not reorder equal elements) and `O(m n + n log n)`
13071308
/// worst-case, where the key function is `O(m)`.
13081309
///
@@ -1329,7 +1330,10 @@ impl<T> [T] {
13291330
where F: FnMut(&T) -> B, B: Ord
13301331
{
13311332
let mut indices: Vec<_> = self.iter().map(f).enumerate().map(|(i, k)| (k, i)).collect();
1332-
indices.sort();
1333+
// The elements of `indices` are unique, as they are indexed, so any sort will be stable
1334+
// with respect to the original slice. We use `sort_unstable` here because it requires less
1335+
// memory allocation.
1336+
indices.sort_unstable();
13331337
for i in 0..self.len() {
13341338
let mut index = indices[i].1;
13351339
while index < i {
@@ -1414,8 +1418,11 @@ impl<T> [T] {
14141418
/// Sorts the slice with a key extraction function, but may not preserve the order of equal
14151419
/// elements.
14161420
///
1421+
/// Note that, currently, the key function for `sort_unstable_by_key` is called multiple times
1422+
/// per element, unlike `sort_stable_by_key`.
1423+
///
14171424
/// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1418-
/// and `O(n log n)` worst-case.
1425+
/// and `O(m n log m n)` worst-case, where the key function is `O(m)`.
14191426
///
14201427
/// # Current implementation
14211428
///
@@ -1425,8 +1432,8 @@ impl<T> [T] {
14251432
/// randomization to avoid degenerate cases, but with a fixed seed to always provide
14261433
/// deterministic behavior.
14271434
///
1428-
/// It is typically faster than stable sorting, except in a few special cases, e.g. when the
1429-
/// slice consists of several concatenated sorted sequences.
1435+
/// Due to its key calling strategy, `sort_unstable_by_key` is likely to be slower than
1436+
/// `sort_by_key` in cases where the key function is expensive.
14301437
///
14311438
/// # Examples
14321439
///

0 commit comments

Comments
 (0)