0% found this document useful (0 votes)
15 views

Activity Selection Problem + Huffman encoding tree

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)
15 views

Activity Selection Problem + Huffman encoding tree

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/ 4

Activity Selection Problem

ActivitySelection(activities)

Sort activities by their finish times

selected = [] // List to store selected activities

selected.append(activities[0]) // Always select the first activity

last_selected = 0 // Index of the last selected activity

for i = 1 to n - 1

if activities[i].start >= activities[last_selected].finish

selected.append(activities[i])

last_selected = i

return selected
What is Huffman Encoding?

Huffman encoding is a Greedy Algorithm used for data compression. It assigns variable-
length binary codes to characters such that:

1. Frequently occurring characters have shorter codes.

2. Infrequently occurring characters have longer codes.

3. The encoding is prefix-free (no code is a prefix of another).

Steps to Build a Huffman Tree

1. Create a Min-Heap:

o Start with leaf nodes for each character and their frequencies.

o Insert these nodes into a min-heap.

2. Build the Tree:

o While there is more than one node in the heap:


1. Remove the two nodes with the smallest frequencies.

2. Create a new internal node with a frequency equal to the sum of the
two nodes' frequencies.

3. Make the two nodes the left and right children of the new node.

4. Insert the new node back into the heap.

3. Generate Codes:

o Traverse the Huffman tree from the root to each leaf node.

o Assign 0 for left traversal and 1 for right traversal.

4. Encode/Decode:

o Use the generated codes to encode or decode the text.

HuffmanEncoding(frequencies)

Create a priority queue (min-heap) of nodes where each node contains:

- A character

- Its frequency

- Left and right children (initially None)

While there is more than one node in the heap:

Extract two nodes with the smallest frequencies (N1, N2)

Create a new node with:

- Frequency = N1.frequency + N2.frequency

- Left child = N1, Right child = N2

Insert the new node back into the heap

The remaining node is the root of the Huffman Tree

Generate codes by traversing the tree:

Traverse(root, code)

If node is a leaf:

Assign 'code' to the character

Otherwise:

Traverse(node.left, code + "0")

Traverse(node.right, code + "1")

Return the character-to-code mapping

You might also like