Prepared By,: Chetan Shetty Assistant Professor Department of CSE Msrit Bangalore
Prepared By,: Chetan Shetty Assistant Professor Department of CSE Msrit Bangalore
Prepared By,: Chetan Shetty Assistant Professor Department of CSE Msrit Bangalore
Chetan Shetty
Assistant Professor
Department of CSE
MSRIT
Bangalore
DIVIDE AND CONQUER
• Divide the problem into sub-problems that are similar to the original
but smaller in size.
Comp 122
MERGESORT
CONT…
CONT…
CONT…
CONT…
CONT…
CONT…
CONT…
CONT…
CONT…
CONT…
CONT…
CONT…
CONT…
CONT…
CONT…
CONT…
CONT…
CONT…
CONT…
CONT…
CONT…
14 23 45 98 6 33 42 67
14 23 45 98 6 33 42 67
Merge
14 23 45 98 6 33 42 67
Merge
14 23 45 98 6 33 42 67
6 14
Merge
14 23 45 98 6 33 42 67
6 14 23
Merge
14 23 45 98 6 33 42 67
6 14 23 33
Merge
14 23 45 98 6 33 42 67
6 14 23 33 42
Merge
14 23 45 98 6 33 42 67
6 14 23 33 42 45
Merge
14 23 45 98 6 33 42 67
6 14 23 33 42 45 67
Merge
14 23 45 98 6 33 42 67
6 14 23 33 42 45 67 98
Merge
ALGORITHM
8 3 2 9 7 1 5 4
T(n)
ì 0 if n =1
ï
T(n) £ í T ( én/2ù ) + T ( ën/2û ) + n otherwise
ï
î solve left half solve right half merging
T(n/2)
T(n/2)
T(n)
T(n)= 2T(n/2) +cn
APPROACHES TO SOLVE RECURSION
Approach 1:
1. Intuitive solution to recurrence is to “unroll” the recursion, accounting for the
running time of first few levels.
3. Sum the running times over all levels of the recursion and thereby arrives at a
total running time.
Step1: Analyze the first few levels.
• 1st level of recursion Single problem of size n O(n)
• 2nd level of recursion 2 problems each of size n/2 O(n/2)
• 3rd level of recursion 4 problems each of size n/4 O(n/4)
T(n) n
...
T(2) T(2) T(2) T(2) T(2) T(2) T(2) T(2) n/2 (2)
41 n log2n
SUBSTITUTING A SOLUTION INTO THE MERGESORT RECURSION