Skip to content

Commit

Permalink
Inlining and comment tweaks
Browse files Browse the repository at this point in the history
  • Loading branch information
ejmount committed Feb 24, 2024
1 parent 5169650 commit 79da205
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/k_smallest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ where
where
F: FnMut(&T, &T) -> bool,
{
#[inline]
fn children_of(n: usize) -> (usize, usize) {
(2 * n + 1, 2 * n + 2)
}
Expand Down Expand Up @@ -47,7 +48,7 @@ where

let mut is_less_than = move |a: &_, b: &_| comparator(a, b) == Ordering::Less;

// Rearrange the into a valid heap by reordering from the second-bottom-most layer up to the root
// Rearrange the storage into a valid heap by reordering from the second-bottom-most layer up to the root
// Slightly faster than ordering on each insert, but only by a factor of lg(k)
// The resulting heap has the **largest** item on top
for i in (0..=(storage.len() / 2)).rev() {
Expand All @@ -59,8 +60,7 @@ where
// So feed them into the heap
// Also avoids unexpected behaviour with restartable iterators
iter.for_each(|val| {
// `for_each` is potentially more performant for deeply nested iterators, see its docs.
if is_less_than(&val, &mut storage[0]) {
if is_less_than(&val, &storage[0]) {
// Treating this as an push-and-pop saves having to write a sift-up implementation
// https://en.wikipedia.org/wiki/Binary_heap#Insert_then_extract
storage[0] = val;
Expand Down Expand Up @@ -88,6 +88,7 @@ where
storage
}

#[inline]
pub(crate) fn key_to_cmp<T, K, F>(key: F) -> impl Fn(&T, &T) -> Ordering
where
F: Fn(&T) -> K,
Expand Down

0 comments on commit 79da205

Please sign in to comment.