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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
| #define _CRT_SECURE_NO_WARNINGS 1 #include"heap.h"
void heapinit(heap* hp) { assert(hp); hp->capacity =hp->size= 0; hp->a = NULL; }
void heapdestroy(heap* hp) { assert(hp); free(hp->a); hp->a = NULL; hp->capacity = hp->size = 0; }
void adjustup(hpdata *a, int n, int child) { assert(a); int parent = (child - 1) / 2; while (child >0) { if (a[child] > a[parent]) { hpdata tmp = a[child]; a[child] = a[parent]; a[parent] = tmp; child = parent; parent = (child - 1) / 2; } else { break; } }
}
void heappush(heap *hp, hpdata x) { assert(hp); if (hp->size == hp->capacity) { size_t newcapcity = hp->capacity == 0 ? 4 : hp->capacity * 2; hpdata *tmp = (hpdata*)realloc(hp->a, sizeof(hpdata)*newcapcity); if (tmp != NULL) { hp->a = tmp; hp->capacity = newcapcity; } else { perror("realloc"); return; } } hp->a[hp->size] = x; hp->size++; adjustup(hp->a, hp->size, hp->size-1);
}
void heapprint(heap*hp) { int i = 0; for (i = 0; i < hp->size; i++) { printf("%d ", hp->a[i]); } }
```c
bool heapempty(heap*hp) { assert(hp); return hp->size == 0;
}
int heapsize(heap*hp) { assert(hp); return hp->size; }
void adjustdown(int *a, int n, int parent) { int child = parent * 2 + 1; while (child < n) { if (child + 1 < n&&a[child + 1] > a[child]) { ++child; } if (a[child] > a[parent]) { swap(&a[child], &a[parent]); parent = child; child = parent * 2 + 1; } else { break; } } }
void heappop(heap*hp) { assert(hp); assert(!heapempty(hp)); swap(&hp->a[0], &hp->a[hp->size - 1]); hp->size--; adjustdown(hp->a, hp->size, 0); }
|