Presentation on theme: "資工研二 翁靜美. L 1 : 1, 2, 5, 6L 2 : 3, 4 124365 Input:Two sorted lists, L 1 = (a 1, a 2,..., a n1 ) and L 2 = (b 1, b 2,..., b n2 ). Output:A sorted list."— Presentation transcript:
L 1 : 1, 2, 5, 6L 2 : 3,
Input:Two sorted lists, L 1 = (a 1, a 2,..., a n1 ) and L 2 = (b 1, b 2,..., b n2 ). Output:A sorted list consisting of elements in L 1 and L 2. Begin i : = 1 j : = 1 do compare a i and b j if a i > b j then output b j and j : = j + 1 else output a i and i : = i + 1 while (i n 1 and j n 2 ) if i > n 1 then output b j, b j+1,..., b n2, else output a i, a i+1,..., a n1. End. The worst case of merge sort L 1 : L 2 : The number of comparison required is m+n-1
If more than two sorted lists are to be merged, we can still apply the linear merge algorithm. These merging processes are called 2-way merge because each merging step only merges two sorted lists.
L2L2 30 elementsL3L3 10 elementsL1L1 50 elements L 1 +L 2 80 elements L 1 +L 2 +L 3 90 elements = = 89 the number of comparisons required in this merging sequence is 168
L2L2 30 elementsL3L3 10 elementsL1L1 50 elements L 2 +L 3 40 elements L 2 +L 3 +L 1 90 elements = = 89 the number of comparisons required is only 128
There are m sorted lists. Each of them consists of n i elements. What is the optimal sequence of merging process to merge these sorted lists together by using the minimum number of comparisons?
Input:m sorted lists, L i, i = 1, 2,..., m, each L i consisting of n i elements. Output:An optimal 2-way merge tree. Step 1: Generate m trees, where each tree has exactly one node (external node) with weight n i. Step 2: Choose two trees T 1 and T 2 with minimal weights. Step 3: Create a new tree T whose root has T 1 and T 2 as its subtrees and weight is equal to the sum of weights T 1 and T 2. Step 4: Replace T 1 and T 2 by T. Step 5: If there is only one tree left, stop and return; otherwise, go to Step 2.
For the given m numbers n 1, n 2, …, n m, we can construct a min-heap to represent these numbers where the root value is smaller than the values of its sons. The main loop is executed (n-1) times: Tree reconstruction after removing the root, which has the smallest value, can be done in O(log n) time. The insertion of a new node into a min-heap also can be done in O(log n) time. The total time to generate an optimal extended binary tree is O(n log n).
In telecommunication, how do we represent a set of messages, each with an access frequency, by a sequence of 0’s and 1’s? To minimize the transmission and decoding costs, we may use short strings to represent more frequently used messages. This problem can by solved by using the 2-way merge algorithm.