Professional Documents
Culture Documents
Mergesort: 25-Feb-21 HK Rana, Dept. of CSE, GUB 1
Mergesort: 25-Feb-21 HK Rana, Dept. of CSE, GUB 1
2. Conquer: The solution of the original problem is formed from the solutions
to the subproblems.
The running time equation of divide and conquer approach:
T(n) = 2T(n/2) + O(n) where n is the input size.
The solution to this equation is O(nlog2n).
2. Conquer: Merge the two sorted subsequences to produce the sorted result.
• Merge sort uses the “merge” step to combine two sorted sublists to create one single
sorted list.
• Suppose A is a sorted list with R elements and B is another sorted list with S elements.
After merging there is only a single sorted list C with N=R+S elements.
(2) Set Center = (Left+Right)/2 (3) Create arrays L[1…n1] and R[1…n2]
(4) For i = 1 to n1
(3) Merge-Sort (A, Left, Center)
(5) do L[i] = A[Left + i -1]
(4) Merge-Sort (A,Center+1, Right)
(6) For j = 1 to n2
(5) Merge(A, Left, Center, Right) (7) do R[j] = A[Center + j]
(6) End (8) i=1
(9) j=1
(10) For k = Left to Right
(11) do if L[i] <= R[j]
(12) then A[k] = L[i]
(13) i=i+1
(14) else A[k] = R[j]
(15) j=j+1
(16) End
5 2 4 1 7 3 2 6
5 2 4 1 7 3 2 6
5 2 4 1 7 3 2 6
5 2 4 1 7 3 2 6
2 5 1 4 3 7 2 6
1 2 4 5 2 3 6 7
1 2 2 3 4 5 6 7
T(1) = 1 For N = 1
Solution:
T(N) = 2T(N/2) + N
T(N/2) = 2T(N/4) + N/2
T(N/4) = 2T(N/8) + N/4
……………………..
T(2) = 2T(1) + 2
By using 2K = N, it is obtained as
T(N) = NT(1) + NLog2N = N + NLog2N = O(NLog2N)