Advertisement
giovani-rubim

Generic Heap

Sep 9th, 2018
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.48 KB | None | 0 0
  1. #define HEAP_SIZE (1 << 15)
  2. typedef int tVal;
  3. typedef int tKey;
  4. typedef struct HeapNode {
  5.     tKey key;
  6.     tVal val;
  7.     int index;
  8. } HeapNode;
  9. HeapNode vHeapNodes[HEAP_SIZE];
  10. HeapNode* lastHeapNode;
  11. HeapNode* heap[HEAP_SIZE];
  12. int heapSize;
  13. void initHeap() {
  14.     lastHeapNode = vHeapNodes - 1;
  15.     heapSize = 0;
  16. }
  17. void heapUpdateNode(HeapNode* node) {
  18.     int index = node->index;
  19.     tKey key = node->key;
  20.     while (index) {
  21.         int parentIndex = (index - 1) >> 1;
  22.         HeapNode* parent = heap[parentIndex];
  23.         if (parent->key >= key) break;
  24.         heap[index] = parent;
  25.         parent->index = index;
  26.         index = parentIndex;
  27.     }
  28.     for (;;) {
  29.         int childIndex = (index << 1) | 1;
  30.         if (childIndex >= heapSize) break;
  31.         HeapNode* child = heap[childIndex];
  32.         int secondChildIndex = childIndex + 1;
  33.         if (secondChildIndex < heapSize) {
  34.             HeapNode* secondChild = heap[secondChildIndex];
  35.             if (secondChild->key > child->key) {
  36.                 child = secondChild;
  37.                 childIndex = secondChildIndex;
  38.             }
  39.         }
  40.         if (child->key <= key) break;
  41.         heap[index] = child;
  42.         child->index = index;
  43.         index = childIndex;
  44.     }
  45.     heap[index] = node;
  46.     node->index = index;
  47. }
  48. HeapNode* heapPush(tVal val, tKey key) {
  49.     HeapNode* node = ++lastHeapNode;
  50.     node->val = val;
  51.     node->key = key;
  52.     node->index = heapSize ++;
  53.     heapUpdateNode(node);
  54.     return node;
  55. }
  56. tVal heapPop() {
  57.     HeapNode* head = heap[0];
  58.     -- heapSize;
  59.     if (heapSize) {
  60.         HeapNode* node = heap[heapSize];
  61.         node->index = 0;
  62.         heapUpdateNode(node);
  63.     }
  64.     return head->val;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement