-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheap.cpp
75 lines (62 loc) · 1.58 KB
/
heap.cpp
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <stdio.h>
#include <stdint.h>
typedef uint32_t u32;
typedef unsigned char u8;
typedef struct HeapNode {
char ch;
u32 freq;
struct HeapNode *left, *right;
u32 code;
u8 codeLength; // how many bits used in code, maximum of 32
} HeapNode;
typedef struct Heap {
u32 size; // current size
u32 capacity; // overall size
struct HeapNode ** array;
} Heap;
void swap(HeapNode **a, HeapNode **b) {
HeapNode *t = *a;
*a = *b;
*b = t;
}
void heapify(Heap * heap, u32 idx)
{
u32 smallest = idx;
u32 left = 2 * idx + 1;
u32 right = 2 * idx + 2;
if (left < heap->size && heap->array[left]->freq < heap->array[smallest]->freq)
smallest = left;
if (right < heap->size && heap->array[right]->freq < heap->array[smallest]->freq)
smallest = right;
if (smallest != idx)
{
swap(&heap->array[smallest], &heap->array[idx]);
heapify(heap, smallest);
}
}
void insertHeap(Heap * heap, HeapNode * node)
{
if (heap->size == heap->capacity)
{
printf("Heap size is at capacity. Nothing inserted.");
return;
}
heap->size++;
u32 i = heap->size - 1;
heap->array[i] = node;
while(i > 0 && heap->array[(i - 1)/2]->freq > heap->array[i]->freq)
{
swap(&heap->array[(i - 1)/2], &heap->array[i]);
i = (i - 1) / 2;
}
}
HeapNode * extractMin(Heap * heap)
{
if (heap->size <= 0)
return NULL;
HeapNode * root = heap->array[0];
heap->array[0] = heap->array[heap->size - 1];
heap->size--;
heapify(heap, 0);
return root;
}