Greedy Algo
Greedy Algo
algorithms
By:
Tulika Garg
3rd CSE
400/05
The Greedy Method
Extended Binary
Tree(EBT) Representing
a 2-way Merge
External node
Internal node
A Greedy Algorithm to generate
an optimal 2-way merge tree
Input: m sorted lists Li,i=1,2,…m each Li consisting
of ni elements
Output:An optimum two way merge tree
Step 1. generate m trees, where each tree has
exactly 1 node(external node)with weight ni
Step 2. choose two trees T1 and T2 with minimal
weights
Step 3. create a new tree T whose root has T1 and
T2 as its subtrees and weight =the sum of weights
of T1 and T2.
Step 4. replace T1 and T2 by T
Step 5. If there is only 1 Tree left stop and
RETURN;otherwise goto step 2
Merging tree for the example
comparisons=
40 L4 L1
50 30.2+10.2+50.1=130
L2 L3
30 10
The 2-way merging problem
E.g. There are 6 sorted lists with
lengths 2, 3, 5, 7, 11 and 13.
The 2-way merging problem
Huffman codes:
A: 10100 B: 10101 C: 1011
D: 100 E: 00 F: 01
G: 11
EXAMPLE
Here K=E-V+1=5-4+1=2
⊕ on rows 1 and
3 e1 e2 e3 e4 e5
C1 1 1 1
C2 1 1 1
2 cycles C1 and C2 are C3 1 1 1
represented by a 0/1 matrix
e1 e2 e3 e4 e5 ⊕ on rows 2 and 3 : empty
C1 1 1 1 row
C2 1 1 1
∵C = C ⊕ C
Minimum Cycle Basis
problem…
The exclusive operation on C2 and C3
produces an empty row which shows
that C3 is a linear combination of C1
and C2.
Thus C3 is discarded .since now the
cycle basis already has two cycles,we
stop as K=2.A minimum cycle basis is
found to be {C1,C2}.
THANK YOU!!