I'm currently trying to implement Huffman's compression algorithm using a Priority Queue (Min Heap). I've found a resource online that could help me, although there is a piece of code I do not understand, and unfortunately I do not find any mandatory explanation about it.
1) In function minHeapify why is left/right equal to 2*idx+1 / 2*idx +2 ?
2)In function insertMinHeap, why are we testing if `Node->frequency < minHeap->array[(i-1)/2]. What is the purpose of (i-1)/2 ?
Any kind of explanation is greatly welcomed. Appreciate your time.
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;
}