From 2c73258d0b73b1fcb53973ebf7cf2c351ae11c2f Mon Sep 17 00:00:00 2001 From: Ewan Mount Date: Sat, 22 Oct 2022 19:52:48 +0100 Subject: [PATCH] Adding short-circuit if there's no children, to save a compare --- src/k_smallest.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/k_smallest.rs b/src/k_smallest.rs index 8141792d3..ab7f19c86 100644 --- a/src/k_smallest.rs +++ b/src/k_smallest.rs @@ -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