Huffman Coding
Huffman Coding
Huffman Coding
Huffman coding is a lossless data compression algorithm that assigns variable-length codes to
input characters based on their frequencies. The greedy approach builds a binary tree by
repeatedly merging the least frequent characters into a single tree node.
Algorithm:
1. Build a priority queue (min-heap) where each node represents a character and its
frequency.
2. Extract two nodes with the lowest frequencies and create a new internal node with the
combined frequency.
3. Insert the new node back into the heap and repeat until only one node remains.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
if (smallest != idx) {
swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[idx]);
minHeapify(minHeap, smallest);
}
}
while (!isSizeOne(minHeap)) {
left = extractMin(minHeap);
right = extractMin(minHeap);
insertMinHeap(minHeap, top);
}
return extractMin(minHeap);
}
int main() {
char data[] = {'a', 'b', 'c', 'd', 'e'};
int freq[] = {5, 9, 12, 13, 16};
int size = sizeof(data) / sizeof(data[0]);
return 0;
}
Explanation:
The fractional knapsack problem is a variation where you can take fractional parts of items. The
greedy approach selects items based on their value-to-weight ratio, starting with the highest ratio.
Algorithm:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int weight;
int value;
float ratio;
} Item;
return maxValue;
}
int main() {
Item items[] = {{10, 60, 0}, {20, 100, 0}, {30, 120, 0}};
int n = sizeof(items) / sizeof(items[0]);
int capacity = 50;