我目前正在尝试使用优先级队列(最小堆)来实现霍夫曼的压缩算法。我在线上找到了可以帮助我的资源,尽管其中有一段我不懂的代码,但是不幸的是,我没有找到任何强制性的解释。
1)在minHeapify函数中,为什么左/右等于2 * idx + 1/2 * idx +2吗?
2)在函数insertMinHeap中,为什么要测试`Node-> frequency
任何一种解释都将受到欢迎。感谢您的时间。
void minHeapify(struct MinHeap* minHeap, int idx)
{
int smallest = idx;
int left = 2 * idx + 1;
int right = 2 * idx + 2;
if (left < minHeap->size && minHeap->array[left]->
freq < minHeap->array[smallest]->freq) //
smallest = left;
if (right < minHeap->size && minHeap->array[right]->
freq < minHeap->array[smallest]->freq)
smallest = right;
if (smallest != idx) {
swapMinHeapNode(&minHeap->array[smallest],
&minHeap->array[idx]);
minHeapify(minHeap, smallest);
}
}
void insertMinHeap(struct MinHeap* minHeap,
struct MinHeapNode* minHeapNode)
{
++minHeap->size;
int i = minHeap->size - 1;
while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq) {
minHeap->array[i] = minHeap->array[(i - 1) / 2];
i = (i - 1) / 2;
}
minHeap->array[i] = minHeapNode;
}