Skip to content

Commit e36bbc8

Browse files
committed
Example of total ord of elements for sort_by
1 parent 7e57f0a commit e36bbc8

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

src/liballoc/slice.rs

+6
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,12 @@ impl<T> [T] {
242242
/// // reverse sorting
243243
/// v.sort_by(|a, b| b.cmp(a));
244244
/// assert!(v == [5, 4, 3, 2, 1]);
245+
///
246+
/// // While f64 doesn't implement Ord because NaN != NaN, we can use
247+
/// // partial_cmp here because we know none of the elements are NaN.
248+
/// let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
249+
/// floats.sort_by(|a, b| a.partial_cmp(b).unwrap());
250+
/// assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
245251
/// ```
246252
#[stable(feature = "rust1", since = "1.0.0")]
247253
#[inline]

src/libcore/slice/mod.rs

+6
Original file line numberDiff line numberDiff line change
@@ -1367,6 +1367,12 @@ impl<T> [T] {
13671367
/// // reverse sorting
13681368
/// v.sort_unstable_by(|a, b| b.cmp(a));
13691369
/// assert!(v == [5, 4, 3, 2, 1]);
1370+
///
1371+
/// // While f64 doesn't implement Ord because NaN != NaN, we can use
1372+
/// // partial_cmp here because we know none of the elements are NaN.
1373+
/// let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
1374+
/// floats.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
1375+
/// assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
13701376
/// ```
13711377
///
13721378
/// [pdqsort]: https://github.com/orlp/pdqsort

0 commit comments

Comments
 (0)