DAA - Lecture 21 - Optimal Merge Patterns
DAA - Lecture 21 - Optimal Merge Patterns
COURSE INSTRUCTOR:
B.VAMSI
Assistant Professor
CSE Department
Department of Computer Science and Engineering Slide No. 1
Topic: Optimal Merge Patterns Course: Design and Analysis of Algorithms
Unit -3 Syllabus:
Greedy method: General method, Applications: Job sequencing with
deadlines, knapsack problem, Single source shortest path problem,
Optimal Merge Patterns
Lecture Objective:
Lecture Contents: Understand the two-way
merging technique
• Procedure
• Example
Lecture Outcome:
• Application Analyze the Huffman Coding
using Optimal Merge
Patterns
Procedure:
• Merging means combining of two sorted lists in to one.
• Example:
A 1 2 3 4
B 5 6 7 8
C 1 2 3 4 5 6 7 8
• These two sorted files containing ‘n’ and ‘m’ records respectively
could be merged together in time is O(n+m).
• When “more than two” sorted files are to be merged together, then
the merge can be accomplished by repeatedly merging sorted files
in pairs is called as “TWO-WAY MERGING”.
Case 1: A B C D
6 5 2 3
Files A B C D
Sizes 6 5 2 3 11
13
Procedure:
16
Case-1 follows ‘linear merging’:
• A followed by B and
Therefore Total time
• B followed by C and = O(11+13+16)
• C followed by D = 40
Case 2: A B C D
6 5 2 3
Files A B C D
Sizes 6 5 2 3 11 5
16
Procedure:
Case-2 follows: Therefore Total time
= O(11+5+16)
• Merge ‘A’ with ‘B’ = 32
• Merge ‘C’ with ‘D’
Case 3: A B C D
6 5 2 3
Files A B C D
Sizes 6 5 2 3 5
10
Procedure:
Case-3 follows: 16
• Merging minimum length of files
Therefore Total time
= O(5+10+16)
= 31
• So, in the above 3 cases, case-3 gives minimum cost to merge four
files, because of merging of minimum length of files first.
• The ‘greedy method’ which we follow always says that merging a
pair of small files to get the best solution.
Algorithm
treenode = record Algorithm Tree(n)
{ {
for i := 1 to n-1 do
treenode *lchild;
{
treenode *rchild;
pt:= new treenode; //create a new node
integer weight;
(pt lchild) := least(list);
}; (pt rchild) := least(list);
(pt weight) := ((pt lchild)weight) + (pt lchild)weight));
Insert(list,pt);
}
return least(list;)
}
Time Complexity: O(n2)
Decoding Process:
• For decoding process, we must carry the “codes” and “Table”.
Character Code
In the table, total alphabets/characters are “5”.
A 001
B 10 So total memory occupies for alphabets in ASCII is
C 11 5*8 = 40 bits.
D 01
Now, the total memory for codes is: 001, 10, 11,
E 000 01, 000 12 bits.
Summary:
• Procedure
• Algorithm
• Example
• Application: Huffman Coding
Exercise:
• Find the time complexity for the files A,B,C,D,E,F
with sizes are: 2, 3, 5, 7, 9, 13 using optimal merge patters?
Thank You