0% found this document useful (0 votes)
1 views15 pages

Algorithm Lab

This document outlines a lab assignment focused on implementing the Huffman coding algorithm in C. It details the code structure, including data structures for the Huffman tree and Min Heap, as well as functions for building the tree, generating codes, and printing results. Additionally, it addresses issues fixed in the code and provides a second problem description related to Huffman coding functionalities.

Uploaded by

ruhani islam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views15 pages

Algorithm Lab

This document outlines a lab assignment focused on implementing the Huffman coding algorithm in C. It details the code structure, including data structures for the Huffman tree and Min Heap, as well as functions for building the tree, generating codes, and printing results. Additionally, it addresses issues fixed in the code and provides a second problem description related to Huffman coding functionalities.

Uploaded by

ruhani islam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Lab Assignment-03

 Course Title: Algorithms Lab


 Course Code: 232

 Submitted To:
Course Instructor: Sumona Yeasmin
Designation: Lecturer
Department: CSE
Bangladesh University of Business and Technology

 Submitted By:
Name -Ruhani Islam
ID-20234103286
Section-7
Intake-52
Program-B.Sc. in CSE
Problem description 1: The following code focuses on the Huffman coding algorithm, Huffman
tree
building, code printing, and other functionalities based on needs.

This is a C code for Huffman Coding . The code sets up the necessary data structures and helper
functions to construct and manage a Min Heap.
Running the Code:
Explanation :
1.
#include <stdio.h>
#include <stdlib.h>
#define MAX_TREE_HT 100
-At first the code starts with Standard I/O and memory allocation libraries and
MAX_TREE_HT is used here to define the maximum tree height.

2.
struct MH_Node {
char character;
unsigned int frequency;
struct MH_Node* l, * r;
};
struct M_Heap {
unsigned size;
unsigned space;
struct MH_Node** array;
};
-MH_Node is used to represent a node in the Huffman tree. It stores a character, its frequency,
and pointers to left and right children.
- M_Heap is used represent a Min Heap It includes the current size, capacity space, and an
array of node pointers.

3.
struct MH_Node* newNode (char character, unsigned int frequency)
 Creating a new node with given character and frequency that returns a pointer to this
node. Memory allocation is done with malloc for the node.
struct M_Heap* createM_Heap (unsigned space)
 Initializing a new Min Heap with a specified capacity , setting its initial size to zero.
void swapMH_Node(struct MH_Node** a, struct MH_Node** b)
 Swapping of two pointers of MH_Node to main the heap tree.
void M_Heapify(struct M_Heap* M_Heap, int idx)
 Maintaining the heap tree elements which includes the parent node should have a
smaller frequency value than its children.
4.
if (r < M_Heap->size && M_Heap->array[r]->frequency < M_Heap->array[smallest]-
>frequency)
smallest = r;
if (smallest!= idx) {
swapMH_Node(&M_Heap->array[smallest], &M_Heap->array[idx]);
M_Heapify(M_Heap, smallest);
}
To check if the right child's frequency is less than the smallest is observed before swapping
nodes .

5.
int isSizeOne(struct M_Heap* M_Heap){
return (M_Heap->size == 1);
}
To check if the heap currently contains only one element.

6.
struct MH_Node* extractMin(struct M_Heap* M_Heap)
{
struct MH_Node* temp = M_Heap->array [0];
M_Heap->array [0] = M_Heap->array[M_Heap->size - 1];
--M_Heap->size;
M_Heapify(M_Heap, 0);
return temp;
}
- This function is used to remove the smallest element from the heap which is always at index
0 the root and returns it. After removing the smallest it replaces the root with the last element in
the heap to maintain the heap property.

7.
void insertM_Heap (struct M_Heap* M_Heap, struct MH_Node* MH_Node)
{
int i = M_Heap->size - 1;
++M_Heap->size;
while (i && MH_Node->frequency < M_Heap->array [(i - 1)/2]->frequency)
{
M_Heap->array[i] = M_Heap->array [(i -1)/2];
i = (i - 1)/2;
}
M_Heap->array[i] = MH_Node;
}
Inserting a new node into the heap. It starts by placing the new node at the end of the heap and
then puts in the right position after swapping with the parent restoring heap property .

8.
void buildM_Heap(struct M_Heap* M_Heap)
{
int n = M_Heap->size - 1;
int i;
for (i = (n - 1) / 2; i >= 0; --i)
M_Heapify (M_Heap, i);
}
The buildM_Heap function calls heapify operation starting from the last non-leaf node to ensure
this remains a min-heap.

9.
void printArr(int arr[], int n)
{
int i;
for (i = 0; i < n; ++i)
printf("%d", arr[i]);
printf("\n");
}
This function prints the binary code for character.
10.
int isLeaf (struct MH_Node* root)
{ return! (root->l) &&! (root->r); }
This function checks if a node is a leaf node or not. As a leaf node does not have left or right
children.

11.
struct M_Heap* createAndBuildM_Heap(char character[], int frequency[], int size)
This function creates a Min-Heap and inserts nodes representing each character and its
frequency into it.
struct MH_Node* buildHuffmanTree(char character[], int frequency[], int size)
struct MH_Node *l, *r, *top;
struct M_Heap* M_Heap = createAndBuildM_Heap(character, frequency, size);
while (!isSizeOne(M_Heap)) {
l = extractMin(M_Heap);
r = extractMin(M_Heap);
top = newNode('$', l->frequency + r->frequency);
top->l = l;
top->r = r;
insertM_Heap(M_Heap, top);
This repeatedly takes the two nodes with the smallest frequencies, combines them into a new
node, and inserts this new node back into the heap. This process continues until there is only one
node left in the heap, which is the root of the Huffman Tree.
12.
void printCodes (struct MH_Node* root, int arr[], int top)
if (root->l) {
arr[top] = 0;
printCodes(root->l, arr, top + 1);
}
if (root->r) {
arr[top] = 1;
printCodes(root->r, arr, top + 1);
}
if (isLeaf(root)) {
printf("%c: ", root->character);
printArr(arr, top);
}
This traverses the Huffman Tree and prints the Huffman codes for each character. It uses an array
to store the path, where going left is 0 and going right adds 1.

13.
int main ()
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f'};
int frequency[] = {5, 9, 12, 13, 16, 45};
int size = sizeof(arr) / sizeof(arr[0]);
HuffmanCodes(arr, frequency, size);
return 0;
This inputs data (characters and their frequencies) and calls HuffmanCodes to execute the code
and prints the Huffman codes for each character.
Output :
Issues I fixed in this code :
1.if (smallest! = idx)
Syntex Error: There is a space between ! and =.
if (smallest !=idx)

2.return! (root->l) &&! (root->r)


Syntex Error: No space is allowed between ! and the expression.
return !(root->l) &&! (root->r);

3. int i = M_Heap->size - 1;

++M_Heap->size;
increasing the heap size after setting i = size - 1,which causes the last element to insert in the
wrong place.
int i = M_Heap->size;
++M_Heap->size;
Problem description 2: Write a program on Huffman coding. There are mainly two major parts
in Huffman Coding. First one is to build a Huffman Tree from input characters, and the second
one is to traverse the Huffman Tree and assign codes to characters, determine-
1. Huffman Code for each character
2. Average code length
3. Length of Huffman encoded message (in bits)
Code :
Explanation :

1. At first the code starts with Standard I/O and dynamic memory allocation libraries string
operations and MAX_CHAR is used here to define the maximum characters
2.
typedef struct Node {
char ch;
int freq;
struct Node *left, *right;
struct Node *next;
} Node;
ch :Stores the character.
freq: Stores the frequency .
left & right: Are pointers to child nodes in the tree.
next: Used for maintaining a sorted linked list (priority queue)
3.
typedef struct Code {

char ch;
char code[20];
} Code;
Stores the Huffman code for each character. A string of '0' and '1' representing the binary code
4.

Node* createNode(char ch, int freq) {

Node* temp = (Node*)malloc(sizeof(Node));

temp->ch = ch;

temp->freq = freq;

temp->left = temp->right = temp->next = NULL;

return temp;

Dynamically it allocates a new node for the Huffman tree.

5.

void insertSorted(Node** head, Node* newNode) {

if (!*head || newNode->freq < (*head)->freq) {

newNode->next = *head;
*head = newNode;

} else {

Node* current = *head;

while (current->next && current->next->freq <= newNode->freq)

current = current->next;

newNode->next = current->next;

current->next = newNode;

Based on frequency it inserts a new node in the linked list which is already sorted in the
ascending form . And
maintains a priority queue (min-heap) .
6.
Node* buildHuffmanTree(char chars[], int freqs[], int size)
Creating a linked list of leaf nodes, each representing a character and its frequency. Repeatedly
taking two nodes with the lowest frequencies and combining them. Lastly returning the root
node of the Huffman tree.
7.
void generateCodes(Node* root, char* code, int depth, Code codes[], int* index, int* totalBits,
int* totalFreq) {
if (root->left) {
code[depth] = '0';
generateCodes(root->left, code, depth + 1, codes, index, totalBits, totalFreq);
}
if (root->right) {
code[depth] = '1';
generateCodes(root->right, code, depth + 1, codes, index, totalBits, totalFreq);
}
if (!root->left && !root->right)
Traversing the Huffman tree, assigning 0 for left and 1 for right .Generating binary Huffman
codes using recursion.
8.
void HuffmanCodes(char chars[], int freqs[], int size) {
Node* root = buildHuffmanTree(chars, freqs, size);
Calls tree builder and initializes all necessary variables. For recursive code generation. For
displaying each character's Huffman code. And lastly to calculate and print the average code
length and total bits.
9.
int main() {
HuffmanCodes(chars, freqs, size);
return 0;
}
Taking user input characters and their frequencies into arrays. Calling the Huffman function ()
and exit.
Output :

You might also like