Greedy Algorithm - Part 1
Greedy Algorithm - Part 1
DATA STRUCTURES
■ For Ringgit Malaysia, the greedy algorithm almost always gives the
optimum solution
A failure of the greedy algorithm
■ In some (fictional) monetary system, eg: in sweden, “krons” come in 1 kron, 7
kron, and 10 kron coins
■ A better solution would be to use two 7 kron pieces and one 1 kron piece
– This only requires three coins
■ Doesn’t guarantee to produce an optimal solution all the time, but it can give
us a globally approximate solution of a given problem in efficient time.
5
Another approach
■ What would be the result if you ran the shortest job first?
■ Again, the running times are 3, 5, 6, 10, 11, 14, 15, 18, and 20 minutes
P1 3 10 15
P2 5 11 18
P3 6 14 20
6
An optimum solution
■ Better solutions do exist:
P1 20 14
P2 18 11 5
P3 15 10 6 3
■ Huffman codes
■ Item i :
– weighs wi
– worth $vi
■ A thief breaks in
Not a full
binary tree
Eg. “abc” is
2. File size must be smallest.
coded as => Can be represented by a full binary tree.
“0101100” => Usually less frequent characters are at bottom
Let C be the alphabet (eg. C={‘a’,’b’,’c’,’d’,’e’,’f’})
For each character c, no. of bits to encode all c’s
occurrences = freqc*depthc
File size B(T) = cCfreqc*depthc
Huffman Code
Huffman Code