about summary refs log tree commit diff
path: root/src/liballoc
diff options
context:
space:
mode:
authorvarkor <github@varkor.com>2018-03-01 12:22:11 +0000
committervarkor <github@varkor.com>2018-03-16 13:57:07 +0000
commitb8452cc3266f2d9567b5c07ca3044b3960e10ebf (patch)
treebf7c8fd7191751f139934e15ca603bbe20bb6488 /src/liballoc
parent670e69e20753e2ef33ee61b0515092cace3fd716 (diff)
downloadrust-b8452cc3266f2d9567b5c07ca3044b3960e10ebf.tar.gz
rust-b8452cc3266f2d9567b5c07ca3044b3960e10ebf.zip
Clarify behaviour of sort_unstable_by_key with respect to sort_by_key
Diffstat (limited to 'src/liballoc')
-rw-r--r--src/liballoc/slice.rs15
1 files changed, 11 insertions, 4 deletions
diff --git a/src/liballoc/slice.rs b/src/liballoc/slice.rs
index db3b14859dd..63b22bd0f6d 100644
--- a/src/liballoc/slice.rs
+++ b/src/liballoc/slice.rs
@@ -1303,6 +1303,7 @@ impl<T> [T] {
     /// Sorts the slice with a key extraction function.
     ///
     /// During sorting, the key function is called only once per element.
+    ///
     /// This sort is stable (i.e. does not reorder equal elements) and `O(m n + n log n)`
     /// worst-case, where the key function is `O(m)`.
     ///
@@ -1329,7 +1330,10 @@ impl<T> [T] {
         where F: FnMut(&T) -> B, B: Ord
     {
         let mut indices: Vec<_> = self.iter().map(f).enumerate().map(|(i, k)| (k, i)).collect();
-        indices.sort();
+        // The elements of `indices` are unique, as they are indexed, so any sort will be stable
+        // with respect to the original slice. We use `sort_unstable` here because it requires less
+        // memory allocation.
+        indices.sort_unstable();
         for i in 0..self.len() {
             let mut index = indices[i].1;
             while index < i {
@@ -1414,8 +1418,11 @@ impl<T> [T] {
     /// Sorts the slice with a key extraction function, but may not preserve the order of equal
     /// elements.
     ///
+    /// Note that, currently, the key function for `sort_unstable_by_key` is called multiple times
+    /// per element, unlike `sort_stable_by_key`.
+    ///
     /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
-    /// and `O(n log n)` worst-case.
+    /// and `O(m n log m n)` worst-case, where the key function is `O(m)`.
     ///
     /// # Current implementation
     ///
@@ -1425,8 +1432,8 @@ impl<T> [T] {
     /// randomization to avoid degenerate cases, but with a fixed seed to always provide
     /// deterministic behavior.
     ///
-    /// It is typically faster than stable sorting, except in a few special cases, e.g. when the
-    /// slice consists of several concatenated sorted sequences.
+    /// Due to its key calling strategy, `sort_unstable_by_key` is likely to be slower than
+    /// `sort_by_key` in cases where the key function is expensive.
     ///
     /// # Examples
     ///