about summary refs log tree commit diff
path: root/src/liballoc
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2018-11-22 06:50:18 +0000
committerbors <bors@rust-lang.org>2018-11-22 06:50:18 +0000
commitf3adec65dd0b05a0a30cd2c134f252e8bece0b76 (patch)
treec54838e3d026957c59ab9cc49a16afd213820961 /src/liballoc
parent4bec59c93baa71d599a616fda9f1180febb08386 (diff)
parent99bed21101ef098393c9e6c8eb64f21892dbc8be (diff)
downloadrust-f3adec65dd0b05a0a30cd2c134f252e8bece0b76.tar.gz
rust-f3adec65dd0b05a0a30cd2c134f252e8bece0b76.zip
Auto merge of #53918 - Havvy:doc-sort-by, r=GuillaumeGomez
Doc total order requirement of sort(_unstable)_by

I took the definition of what a total order is from the Ord trait
docs. I specifically put "elements of the slice" because if you
have a slice of f64s, but know none are NaN, then sorting by
partial ord is total in this case. I'm not sure if I should give
such an example in the docs or not.

r? @GuillaumeGomez
Diffstat (limited to 'src/liballoc')
-rw-r--r--src/liballoc/slice.rs16
1 files changed, 16 insertions, 0 deletions
diff --git a/src/liballoc/slice.rs b/src/liballoc/slice.rs
index 1eaff7410ea..22da9dd6e96 100644
--- a/src/liballoc/slice.rs
+++ b/src/liballoc/slice.rs
@@ -213,6 +213,22 @@ impl<T> [T] {
     ///
     /// This sort is stable (i.e. does not reorder equal elements) and `O(n log n)` worst-case.
     ///
+    /// The comparator function must define a total ordering for the elements in the slice. If
+    /// the ordering is not total, the order of the elements is unspecified. An order is a
+    /// total order if it is (for all a, b and c):
+    ///
+    /// * total and antisymmetric: exactly one of a < b, a == b or a > b is true; and
+    /// * transitive, a < b and b < c implies a < c. The same must hold for both == and >.
+    ///
+    /// For example, while [`f64`] doesn't implement [`Ord`] because `NaN != NaN`, we can use
+    /// `partial_cmp` as our sort function when we know the slice doesn't contain a `NaN`.
+    ///
+    /// ```
+    /// let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
+    /// floats.sort_by(|a, b| a.partial_cmp(b).unwrap());
+    /// assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
+    /// ```
+    ///
     /// When applicable, unstable sorting is preferred because it is generally faster than stable
     /// sorting and it doesn't allocate auxiliary memory.
     /// See [`sort_unstable_by`](#method.sort_unstable_by).