Skip to content

Commit ea6a1bd

Browse files
committed
Compute each key only one during slice::sort_by_key
1 parent ff2d506 commit ea6a1bd

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

src/liballoc/slice.rs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1328,10 +1328,18 @@ impl<T> [T] {
13281328
/// ```
13291329
#[stable(feature = "slice_sort_by_key", since = "1.7.0")]
13301330
#[inline]
1331-
pub fn sort_by_key<B, F>(&mut self, mut f: F)
1331+
pub fn sort_by_key<B, F>(&mut self, f: F)
13321332
where F: FnMut(&T) -> B, B: Ord
13331333
{
1334-
merge_sort(self, |a, b| f(a).lt(&f(b)));
1334+
let mut indices: Vec<_> = self.iter().map(f).enumerate().map(|(i, k)| (k, i)).collect();
1335+
indices.sort();
1336+
for i in 0..self.len() {
1337+
let mut index = indices[i].1;
1338+
while index < i {
1339+
index = indices[index].1;
1340+
}
1341+
self.swap(i, index);
1342+
}
13351343
}
13361344

13371345
/// Sorts the slice, but may not preserve the order of equal elements.

0 commit comments

Comments
 (0)