greedy_algorithms_notes
greedy_algorithms_notes
4. Huffman Coding
Build optimal prefix code by repeatedly merging two smallest-weight nodes (greedy choice).
BEGIN
Create forest: each symbol is a tree with weight = frequency
WHILE more than one tree exists DO
Extract two trees with smallest weights
Create new node with weight = sum of weights
Make the two trees its children
Insert new tree back into forest
ENDWHILE
Assign binary codes by traversing the final tree (0 for left, 1 for right)
OUTPUT codes for all symbols
END
6. Dijkstra's Algorithm
Find shortest paths from source. Greedy: pick the closest unvisited vertex next.
BEGIN
Initialize dist[v] <- INF for all v; dist[source] <- 0
Set S (visited) <- empty
WHILE there are unvisited vertices DO
u <- vertex with minimum dist[] not in S
Add u to S
FOR each neighbor v of u DO
IF dist[u] + weight(u,v) < dist[v] THEN
dist[v] <- dist[u] + weight(u,v)
ENDIF
ENDFOR
ENDWHILE
OUTPUT dist[] for all vertices
END