diff options
Diffstat (limited to 'src/transaction-heap.c')
| -rw-r--r-- | src/transaction-heap.c | 60 |
1 files changed, 60 insertions, 0 deletions
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 @@ | |||
| 1 | // transaction-heap.c | ||
| 2 | #include "transaction-heap.h" | ||
| 3 | #include "utils.h" | ||
| 4 | |||
| 5 | void | ||
| 6 | transaction_heap__pop (struct transaction_heap *heap) | ||
| 7 | { | ||
| 8 | ASSERT (heap != NULL); | ||
| 9 | ASSERT (heap->count > 0); | ||
| 10 | |||
| 11 | heap->array[0] = heap->array[--heap->count]; | ||
| 12 | |||
| 13 | int current = 0; | ||
| 14 | loop: { | ||
| 15 | int left = 2*current + 1; | ||
| 16 | int right = 2*current + 2; | ||
| 17 | int smallest = current; | ||
| 18 | |||
| 19 | if (left < heap->count && | ||
| 20 | heap->array[left].normalized < heap->array[smallest].normalized) { | ||
| 21 | smallest = left; | ||
| 22 | } | ||
| 23 | if (right < heap->count && | ||
| 24 | heap->array[right].normalized < heap->array[smallest].normalized) { | ||
| 25 | smallest = right; | ||
| 26 | } | ||
| 27 | |||
| 28 | if (smallest != current) { | ||
| 29 | struct transaction temp = heap->array[current]; | ||
| 30 | heap->array[current] = heap->array[smallest]; | ||
| 31 | heap->array[smallest] = temp; | ||
| 32 | current = smallest; | ||
| 33 | goto loop; | ||
| 34 | } | ||
| 35 | } | ||
| 36 | } | ||
| 37 | |||
| 38 | void | ||
| 39 | transaction_heap__push (struct transaction_heap *heap, struct transaction value) | ||
| 40 | { | ||
| 41 | ASSERT (heap != NULL); | ||
| 42 | |||
| 43 | if (heap->count > 0 && value.normalized < heap->array[0].normalized) | ||
| 44 | return; | ||
| 45 | |||
| 46 | if (heap->count == ARRAY_LENGTH (heap->array)) | ||
| 47 | transaction_heap__pop (heap); | ||
| 48 | |||
| 49 | heap->array[heap->count++] = value; | ||
| 50 | // bottom up, parent = (current - 1)/2 | ||
| 51 | for (int current = heap->count - 1; | ||
| 52 | current > 0 && | ||
| 53 | heap->array[(current - 1)/2].normalized > heap->array[current].normalized; | ||
| 54 | current = (current - 1)/2) { | ||
| 55 | struct transaction temp = heap->array[(current - 1)/2]; | ||
| 56 | heap->array[(current - 1)/2] = heap->array[current]; | ||
| 57 | heap->array[current] = temp; | ||
| 58 | } | ||
| 59 | } | ||
| 60 | // transaction-heap.c ends here | ||
