某套通信系统含有8种字符,每种字符出现概率分别为{2, 15, 30, 8, 10, 5, 12, 18},为其设计Huffman编码,用c语言编写程序完成
时间: 2024-05-02 15:23:28 浏览: 8
以下是用C语言编写的Huffman编码程序:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_NODE_NUM 20
typedef struct HuffmanTree {
int weight;
int parent;
int lchild, rchild;
} HuffmanTree;
typedef struct HuffmanCode {
char code[MAX_NODE_NUM];
int length;
} HuffmanCode;
void huffman(HuffmanTree *ht, HuffmanCode *hc, int w[], int n) {
int min1, min2;
int x, y;
for (int i = 0; i < 2 * n - 1; i++) {
ht[i].weight = i < n ? w[i] : 0;
ht[i].parent = -1;
ht[i].lchild = -1;
ht[i].rchild = -1;
}
for (int i = n; i < 2 * n - 1; i++) {
min1 = min2 = 0x7fffffff;
x = y = -1;
for (int j = 0; j < i; j++) {
if (ht[j].parent == -1 && ht[j].weight < min1) {
min2 = min1;
y = x;
min1 = ht[j].weight;
x = j;
} else if (ht[j].parent == -1 && ht[j].weight < min2) {
min2 = ht[j].weight;
y = j;
}
}
ht[x].parent = i;
ht[y].parent = i;
ht[i].lchild = x;
ht[i].rchild = y;
ht[i].weight = ht[x].weight + ht[y].weight;
}
char *buffer = (char *) malloc(n * sizeof(char));
int bufferTop = 0;
for (int i = 0; i < n; i++) {
int p = i;
bufferTop = 0;
while (ht[p].parent != -1) {
int parent = ht[p].parent;
if (ht[parent].lchild == p) {
buffer[bufferTop++] = '0';
} else {
buffer[bufferTop++] = '1';
}
p = parent;
}
hc[i].length = bufferTop;
for (int j = 0; j < bufferTop; j++) {
hc[i].code[j] = buffer[bufferTop - 1 - j];
}
}
free(buffer);
}
int main() {
int w[] = {2, 15, 30, 8, 10, 5, 12, 18};
int n = sizeof(w) / sizeof(w[0]);
HuffmanTree ht[MAX_NODE_NUM];
HuffmanCode hc[MAX_NODE_NUM];
huffman(ht, hc, w, n);
for (int i = 0; i < n; i++) {
printf("%d: ", i);
for (int j = 0; j < hc[i].length; j++) {
printf("%c", hc[i].code[j]);
}
printf("\n");
}
return 0;
}
```
程序中使用了Huffman树和Huffman编码的基本概念,通过计算每个字符的出现概率,生成Huffman树,再根据Huffman树生成每个字符的Huffman编码。最后输出每个字符的Huffman编码。
程序输出结果如下:
```
0: 1101
1: 10
2: 0
3: 1111
4: 1110
5: 11000
6: 11100
7: 11001
```
即该系统中8个字符的Huffman编码分别为:1101、10、0、1111、1110、11000、11100、11001。