堆化
二叉堆一般用数组来表示。例如,根节点在数组中的位置是0,第n个位置的子节点分别在2n+1和 2n+2。 因此,第0个位置的子节点在1和2,1的子节点在3和4。以此类推。这种存储方式便于寻找父节点和子节点。在二叉堆上可以进行插入节点、删除节点、取出值最小的节点、减小节点的值等基本操作。
“最小堆”的定义如下:
typedef struct _otherInfo
{
int i;
int j;
}OtherInfo;
typedef struct _minHeapNode
{
int value;
OtherInfo otherInfo;
}MinHeapNode, *PMinHeapNode;
typedef struct _minPQ {
PMinHeapNode heap_array; // 指向堆元素数组
int heap_size; // 当前堆中的元素个数
int capacity; //堆数组的大小
}MinHeap, *PMinHeap;
请实现最小堆的四个辅助函数:
int parent(int i); //返回堆元素数组下标为 i 的结点的父结点下标
int left(int i); //返回堆元素数组下标为 i 的结点的左子结点下标
int right(int i); //返回堆元素数组下标为 i 的结点的右子结点下标
void swap_node(MinHeapNode *x, MinHeapNode *y); //交换两个堆元素的值
答案
#include <stdio.h>
#include <stdlib.h>
#include "minbinheap.h" // 请不要删除,否则检查不通过
int parent(int i){
if(i==0)return -1;
return (i%2==1)?(i-1)/2:(i-2)/2;
}
int left(int i){
return 2*i+1;
}
int right(int i){
return 2*i+2;
}
void swap_node(MinHeapNode *x, MinHeapNode *y){
int t=x->value;
x->value=y->value;
y->value=t;
t=x->otherInfo.i;
x->otherInfo.i=y->otherInfo.i;
y->otherInfo.i=t;
t=x->otherInfo.j;
x->otherInfo.j=y->otherInfo.j;
y->otherInfo.j=t;
}