Skip to content

Commit

Permalink
Adding short-circuit if there's no children, to save a compare
Browse files Browse the repository at this point in the history
  • Loading branch information
ejmount committed Feb 20, 2024
1 parent f1ccf22 commit 2c73258
Showing 1 changed file with 4 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/k_smallest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,10 @@ where
let (left_idx, right_idx) = children_of(origin);
let (left_item, right_item) = (self.get(left_idx), self.get(right_idx));

if left_item.is_none() { // the left is the earlier child, so if it doesn't exist there's nothing to swap with
return;
}

let cmp = self
.compare(left_item, right_item)
.unwrap_or(Ordering::Greater); // The right item may not exist, so default to picking the left, i.e. lower
Expand Down

0 comments on commit 2c73258

Please # to comment.