#include <stdio.h>
int heap_size = 10;
void max_heapify(int *A, int i){ //维持最大堆性质
int l = 2 * i + 1;
int r = 2 * i + 2;
int largest = 0;
if(l <= heap_size-1 && A[l] > A[i])
largest = l;
else largest = i;
if(r <= heap_size-1 && A[r] > A[largest])
largest = r;
if(i != largest){
int temp = A[i];
A[i] = A[largest];
A[largest] = temp;
max_heapify(A, largest);
}
}
void build_heap(int *A){ //建堆
int k;
for(k = heap_size / 2 - 1; k >= 0; k--){
max_heapify(A, k);
}
}
void heap_sort(int *A){ //对数组使用堆排序
build_heap(A);
int k;
for(k = heap_size - 1; k >= 1; k--){
int temp = A[0];
A[0] = A[k];
A[k] = temp;
heap_size--;
max_heapify(A, 0);
}
}
int heap_maximum(int *A){ //取得优先级队列中的最大元素
return A[0];
}
void heap_extract_max(int *A){ //优先级队列中的最大元素出队
int max = A[0];
A[0] = A[heap_size - 1];
heap_size--;
max_heapify(A, 0);
}
void heap_increase_key(int *A, int i, int key){ //将优先级队列中给定位置的值增加到指定值
if(key < A[i]){
printf("%s", "Error: The key should be bigger than the current value in i!");
return;
}
A[i] = key;
while(i > 0 && A[i] > A[i/2]){
int temp = A[i];
A[i] = A[i/2];
A[i/2] = temp;
i = i/2;
}
}
void heap_insert(int *A, int key){ //向优先级队列中加入一个元素
heap_size++;
A[heap_size - 1] = -1;
heap_increase_key(A, heap_size - 1, key);
}
void heap_output(int *A, int heap_size){ //输出堆中元素
int i;
for(i=0; i<heap_size; i++){
printf("%d ", A[i]);
}
printf("%c", '\n');
}
int main(){ //测试
int A[] = {3,5,8,2,7,10,1,0,32,4};
int i;
printf("%s", "Build heap...\n");
build_heap(A);
heap_output(A, heap_size);
printf("The max value of this heap is %d.\n", heap_maximum(A));
int increase_index = 1, key = 35;
printf("Increase No. %d to %d.\n", increase_index, key);
heap_increase_key(A, 1, 35);
heap_output(A, heap_size);
printf("Extract the maximum number of this heap.\n");
heap_extract_max(A);
heap_output(A, heap_size);
int insert_value = 100;
printf("Insert the value %d to this heap.\n", insert_value);
heap_insert(A, 100);
heap_output(A, heap_size);
printf("Sort this heap.\n");
int heap_size_before_sort = heap_size;
heap_sort(A);
heap_output(A, heap_size_before_sort);
}