1. 堆的基本概念
堆是一种特殊的完全二叉树,它满足以下性质:
- 结构性:除最后一层外,其他层的节点都是满的,最后一层的节点都靠左排列。
- 堆序性:父节点的值总是大于或等于(最大堆)或小于或等于(最小堆)其子节点的值。
堆通常用数组实现,对于数组中的任意元素i:
- 左子节点:2i + 1
- 右子节点:2i + 2
- 父节点:(i - 1) / 2
2. 最大堆(Max Heap)
在最大堆中,父节点的值总是大于或等于其子节点的值。根节点是整个堆中的最大元素。
最大堆的操作
下面是最大堆的基本操作实现:
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void max_heapify(int arr[], int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest])
largest = left;
if (right < n && arr[right] > arr[largest])
largest = right;
if (largest != i) {
swap(&arr[i], &arr[largest]);
max_heapify(arr, n, largest);
}
}
void build_max_heap(int arr[], int n) {
for (int i = n / 2 - 1; i >= 0; i--)
max_heapify(arr, n, i);
}
void insert_max_heap(int arr[], int *n, int key) {
if (*n >= MAX_SIZE) {
printf("堆已满,无法插入\n");
return;
}