Skip to content

Commit 7af04ad

Browse files
committed
Implement partial_sort_unstable for slice
Signed-off-by: tison <wander4096@gmail.com>
1 parent 7934bbd commit 7af04ad

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

library/core/src/slice/mod.rs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3242,6 +3242,50 @@ impl<T> [T] {
32423242
sort::unstable::sort(self, &mut |a, b| f(a).lt(&f(b)));
32433243
}
32443244

3245+
/// Partially sorts the slice in ascending order **without** preserving the initial order
3246+
/// of equal elements.
3247+
#[unstable(feature = "slice_partial_sort_unstable", issue = "149046")]
3248+
#[inline]
3249+
pub fn partial_sort_unstable<R>(&mut self, range: R)
3250+
where
3251+
T: Ord,
3252+
R: RangeBounds<usize>,
3253+
{
3254+
self.partial_sort_unstable_by(range, T::cmp);
3255+
}
3256+
3257+
/// Partially sorts the slice in ascending order with a comparison function, **without**
3258+
/// preserving the initial order of equal elements.
3259+
#[unstable(feature = "slice_partial_sort_unstable", issue = "149046")]
3260+
#[inline]
3261+
pub fn partial_sort_unstable_by<F, R>(&mut self, range: R, mut compare: F)
3262+
where
3263+
F: FnMut(&T, &T) -> Ordering,
3264+
R: RangeBounds<usize>,
3265+
{
3266+
let len = self.len();
3267+
let Range { start, end } = range(range, ..len);
3268+
3269+
sort::select::partition_at_index(self, start, |a: &T, b: &T| compare(a, b) == Less);
3270+
sort::select::partition_at_index(&mut self[start..], end - start, |a: &T, b: &T| {
3271+
compare(a, b) == Less
3272+
});
3273+
sort::unstable::sort(&mut self[start..end], &mut |a, b| compare(a, b) == Less);
3274+
}
3275+
3276+
/// Partially sorts the slice in ascending order with a key extraction function, **without**
3277+
/// preserving the initial order of equal elements.
3278+
#[unstable(feature = "slice_partial_sort_unstable", issue = "149046")]
3279+
#[inline]
3280+
pub fn partial_sort_unstable_by_key<K, F, R>(&mut self, range: R, mut f: F)
3281+
where
3282+
F: FnMut(&T) -> K,
3283+
K: Ord,
3284+
R: RangeBounds<usize>,
3285+
{
3286+
self.partial_sort_unstable_by(range, |a, b| f(a).cmp(&f(b)));
3287+
}
3288+
32453289
/// Reorders the slice such that the element at `index` is at a sort-order position. All
32463290
/// elements before `index` will be `<=` to this value, and all elements after will be `>=` to
32473291
/// it.

0 commit comments

Comments
 (0)