Skip to content

Commit c103d07

Browse files
Add function for removing arbitrary nodes in binaryheap.
This commit introduces binaryheap_remove_node(), which can be used to remove any node from a binary heap. The implementation is straightforward. The target node is replaced with the last node in the heap, and then we sift as needed to preserve the heap property. This new function is intended for use in a follow-up commit that will improve the performance of pg_restore. Reviewed-by: Tom Lane Discussion: https://postgr.es/m/3612876.1689443232%40sss.pgh.pa.us
1 parent 83223f5 commit c103d07

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/common/binaryheap.c

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,35 @@ binaryheap_remove_first(binaryheap *heap)
215215
return result;
216216
}
217217

218+
/*
219+
* binaryheap_remove_node
220+
*
221+
* Removes the nth (zero based) node from the heap. The caller must ensure
222+
* that there are at least (n + 1) nodes in the heap. O(log n) worst case.
223+
*/
224+
void
225+
binaryheap_remove_node(binaryheap *heap, int n)
226+
{
227+
int cmp;
228+
229+
Assert(!binaryheap_empty(heap) && heap->bh_has_heap_property);
230+
Assert(n >= 0 && n < heap->bh_size);
231+
232+
/* compare last node to the one that is being removed */
233+
cmp = heap->bh_compare(heap->bh_nodes[--heap->bh_size],
234+
heap->bh_nodes[n],
235+
heap->bh_arg);
236+
237+
/* remove the last node, placing it in the vacated entry */
238+
heap->bh_nodes[n] = heap->bh_nodes[heap->bh_size];
239+
240+
/* sift as needed to preserve the heap property */
241+
if (cmp > 0)
242+
sift_up(heap, n);
243+
else if (cmp < 0)
244+
sift_down(heap, n);
245+
}
246+
218247
/*
219248
* binaryheap_replace_first
220249
*

src/include/lib/binaryheap.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,11 @@ extern void binaryheap_build(binaryheap *heap);
5959
extern void binaryheap_add(binaryheap *heap, bh_node_type d);
6060
extern bh_node_type binaryheap_first(binaryheap *heap);
6161
extern bh_node_type binaryheap_remove_first(binaryheap *heap);
62+
extern void binaryheap_remove_node(binaryheap *heap, int n);
6263
extern void binaryheap_replace_first(binaryheap *heap, bh_node_type d);
6364

6465
#define binaryheap_empty(h) ((h)->bh_size == 0)
66+
#define binaryheap_size(h) ((h)->bh_size)
67+
#define binaryheap_get_node(h, n) ((h)->bh_nodes[n])
6568

6669
#endif /* BINARYHEAP_H */

0 commit comments

Comments
 (0)