3.5 Optimal Merge Patterns
3.5 Optimal Merge Patterns
If we have two sorted files containing ‘m’ and ‘n’ records then they
could be merged together to obtain one sorted file in time O(m+n).
pairing methods.
Method-1 Method-2
Merge x1 and x2 to get a file y1. Merge x1 and x2 to get a file y1.
Merge y1 and x3 to get y2. Merge x3 and x4 to get a file y2.
Merge y2 and x4 to get desired sorted file. Merge y1 and y2 to get desired sorted file.
records each.
Method-1 Method-2
Operation Moves Operation Moves
Merge x1 and x2 to get file y1 50 Merge x2 and x3 to get file y1 30
Merge y1 with x3 to get 60 Merge y1 with x1 to get 60
desired sorted file desired sorted file
Total Record moves 110 Total Record moves 90
X6= 53 X7 = 91 X8 = 35 X9 = 3 X10 = 11
Z7 179 175 Z8
Operation Moves
Z6 126 53 X6 84 91
Merge X9 with X4 to get Z1 8 X5 X7
Merge Z1 with X10 to get Z2 19 Z5 91
35 X8
Merge Z2 with X3 to get Z3 31
Merge Z3 with X1 to get Z4 59 Z4 59 32 X2
Merge Z4 with X2 to get Z5 91 Z3 31
Merge Z5 with X8 to get Z6 126
28 X1
Z2 19
Merge Z6 with X6 to get Z7 179 12 X3 Fig: Binary Tree
Merge X5 with X7 to get Z8 175 representing Merge
Z1 8 Pattern
Merge Z7 with Z8 to get Z9 354 11 X10
Total Moves 1042
X9 3 5 X4
Find optimal merge pattern for five files whose record lengths are 20, 30, 10, 5, 30.
X1 = 20 X2 = 30 X3 = 10 X4 = 5 X5 = 30 95 Z4
Operation Moves
Merge X4 with X3 to get Z1 15 Z2 35 Z3 60
Merge Z1 with X1 to get Z2 35
Merge X2 with X5 to get Z3 60
Z1 15 20 30 30
Merge Z2 with Z3 to get Z4 95 X1 X2 X5
Total Moves 205
5 10
X4 X3
Fig: Binary Tree representing Merge Pattern