From 00b54af993573b69fef97222eb7d67a32aef69de Mon Sep 17 00:00:00 2001 From: ChangAo Chen Date: Mon, 28 Oct 2024 22:54:37 +0800 Subject: [PATCH v1] Reduce one comparison in binaryheap's sift down --- src/common/binaryheap.c | 44 ++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 23 deletions(-) diff --git a/src/common/binaryheap.c b/src/common/binaryheap.c index 7377ebdf15..c0a647b2a6 100644 --- a/src/common/binaryheap.c +++ b/src/common/binaryheap.c @@ -323,42 +323,40 @@ sift_down(binaryheap *heap, int node_off) { int left_off = left_offset(node_off); int right_off = right_offset(node_off); - int swap_off = 0; - - /* Is the left child larger than the parent? */ - if (left_off < heap->bh_size && - heap->bh_compare(node_val, - heap->bh_nodes[left_off], - heap->bh_arg) < 0) - swap_off = left_off; - - /* Is the right child larger than the parent? */ - if (right_off < heap->bh_size && - heap->bh_compare(node_val, - heap->bh_nodes[right_off], - heap->bh_arg) < 0) + int larger_off; + + Assert(left_off > 0 && left_off < right_off); + + /* Get the larger child */ + if (right_off < heap->bh_size) { - /* swap with the larger child */ - if (!swap_off || - heap->bh_compare(heap->bh_nodes[left_off], + if (heap->bh_compare(heap->bh_nodes[left_off], heap->bh_nodes[right_off], heap->bh_arg) < 0) - swap_off = right_off; + larger_off = right_off; + else + larger_off = left_off; } + else if (left_off < heap->bh_size) + larger_off = left_off; + else + break; /* - * If we didn't find anything to swap, the heap condition is - * satisfied, and we're done. + * If the larger child is less than or equal to the + * parent, we're done. */ - if (!swap_off) + if (heap->bh_compare(node_val, + heap->bh_nodes[larger_off], + heap->bh_arg) >= 0) break; /* * Otherwise, swap the hole with the child that violates the heap * property; then go on to check its children. */ - heap->bh_nodes[node_off] = heap->bh_nodes[swap_off]; - node_off = swap_off; + heap->bh_nodes[node_off] = heap->bh_nodes[larger_off]; + node_off = larger_off; } /* Re-fill the hole */ heap->bh_nodes[node_off] = node_val; -- 2.34.1