aboutsummaryrefslogtreecommitdiff
path: root/src/transaction-heap.c
blob: 038b634e553bcc603aab00816ad4ad7edbb19bd2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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