This commit is contained in:
krahets
2023-04-18 20:19:07 +08:00
parent cf4a59e3d6
commit 363f1f4b5f
25 changed files with 1910 additions and 107 deletions
+12 -1
View File
@@ -102,7 +102,18 @@ comments: true
=== "C"
```c title="my_heap.c"
[class]{maxHeap}-[func]{newMaxHeap}
/* 构造函数,根据切片建堆 */
maxHeap *newMaxHeap(int nums[], int size) {
// 所有元素入堆
maxHeap *h = (maxHeap *)malloc(sizeof(maxHeap));
h->size = size;
memcpy(h->data, nums, size * sizeof(int));
for (int i = size - 1; i >= 0; i--) {
// 堆化除叶节点以外的其他所有节点
siftDown(h, i);
}
return h;
}
```
=== "C#"
+87 -9
View File
@@ -255,7 +255,7 @@ comments: true
=== "C"
```c title="heap.c"
// C 未提供内置 Heap 类
```
=== "C#"
@@ -440,11 +440,20 @@ comments: true
=== "C"
```c title="my_heap.c"
[class]{maxHeap}-[func]{left}
/* 获取左子节点索引 */
int left(maxHeap *h, int i) {
return 2 * i + 1;
}
[class]{maxHeap}-[func]{right}
/* 获取右子节点索引 */
int right(maxHeap *h, int i) {
return 2 * i + 2;
}
[class]{maxHeap}-[func]{parent}
/* 获取父节点索引 */
int parent(maxHeap *h, int i) {
return (i - 1) / 2;
}
```
=== "C#"
@@ -568,7 +577,10 @@ comments: true
=== "C"
```c title="my_heap.c"
[class]{maxHeap}-[func]{peek}
/* 访问堆顶元素 */
int peek(maxHeap *h) {
return h->data[0];
}
```
=== "C#"
@@ -786,9 +798,36 @@ comments: true
=== "C"
```c title="my_heap.c"
[class]{maxHeap}-[func]{push}
/* 元素入堆 */
void push(maxHeap *h, int val) {
// 默认情况下,不应该添加这么多节点
if (h->size == MAX_SIZE) {
printf("heap is full!");
return;
}
// 添加节点
h->data[h->size] = val;
h->size++;
[class]{maxHeap}-[func]{siftUp}
// 从底至顶堆化
siftUp(h, h->size - 1);
}
/* 从节点 i 开始,从底至顶堆化 */
void siftUp(maxHeap *h, int i) {
while (true) {
// 获取节点 i 的父节点
int p = parent(h, i);
// 当“越过根节点”或“节点无需修复”时,结束堆化
if (p < 0 || h->data[i] <= h->data[p]) {
break;
}
// 交换两节点
swap(h, i, p);
// 循环向上堆化
i = p;
}
}
```
=== "C#"
@@ -1148,9 +1187,48 @@ comments: true
=== "C"
```c title="my_heap.c"
[class]{maxHeap}-[func]{pop}
/* 元素出堆 */
int pop(maxHeap *h) {
// 判空处理
if (isEmpty(h)) {
printf("heap is empty!");
return INT_MAX;
}
// 交换根节点与最右叶节点(即交换首元素与尾元素)
swap(h, 0, size(h) - 1);
// 删除节点
int val = h->data[h->size - 1];
h->size--;
// 从顶至底堆化
siftDown(h, 0);
[class]{maxHeap}-[func]{siftDown}
// 返回堆顶元素
return val;
}
/* 从节点 i 开始,从顶至底堆化 */
void siftDown(maxHeap *h, int i) {
while (true) {
// 判断节点 i, l, r 中值最大的节点,记为 max
int l = left(h, i);
int r = right(h, i);
int max = i;
if (l < size(h) && h->data[l] > h->data[max]) {
max = l;
}
if (r < size(h) && h->data[r] > h->data[max]) {
max = r;
}
// 若节点 i 最大或索引 l, r 越界,则无需继续堆化,跳出
if (max == i) {
break;
}
// 交换两节点
swap(h, i, max);
// 循环向下堆化
i = max;
}
}
```
=== "C#"