From 776276d5c7e67356a880f3e31076d32cdc1c1882 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Tue, 10 Nov 2026 11:29:58 +0300 Subject: publish --- src/transaction-heap.c | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 src/transaction-heap.c (limited to 'src/transaction-heap.c') diff --git a/src/transaction-heap.c b/src/transaction-heap.c new file mode 100644 index 0000000..038b634 --- /dev/null +++ b/src/transaction-heap.c @@ -0,0 +1,60 @@ +// transaction-heap.c +#include "transaction-heap.h" +#include "utils.h" + +void +transaction_heap__pop (struct transaction_heap *heap) +{ + ASSERT (heap != NULL); + ASSERT (heap->count > 0); + + heap->array[0] = heap->array[--heap->count]; + + int current = 0; + loop: { + int left = 2*current + 1; + int right = 2*current + 2; + int smallest = current; + + if (left < heap->count && + heap->array[left].normalized < heap->array[smallest].normalized) { + smallest = left; + } + if (right < heap->count && + heap->array[right].normalized < heap->array[smallest].normalized) { + smallest = right; + } + + if (smallest != current) { + struct transaction temp = heap->array[current]; + heap->array[current] = heap->array[smallest]; + heap->array[smallest] = temp; + current = smallest; + goto loop; + } + } +} + +void +transaction_heap__push (struct transaction_heap *heap, struct transaction value) +{ + ASSERT (heap != NULL); + + if (heap->count > 0 && value.normalized < heap->array[0].normalized) + return; + + if (heap->count == ARRAY_LENGTH (heap->array)) + transaction_heap__pop (heap); + + heap->array[heap->count++] = value; + // bottom up, parent = (current - 1)/2 + for (int current = heap->count - 1; + current > 0 && + heap->array[(current - 1)/2].normalized > heap->array[current].normalized; + current = (current - 1)/2) { + struct transaction temp = heap->array[(current - 1)/2]; + heap->array[(current - 1)/2] = heap->array[current]; + heap->array[current] = temp; + } +} +// transaction-heap.c ends here -- cgit v1.3.1