Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Prepared By,: Chetan Shetty Assistant Professor Department of CSE Msrit Bangalore

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 42

Prepared by,

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.

• Conquer the sub-problems by solving them recursively. If they are


small enough, just solve them in a straightforward manner.

• Combine the solutions to create a solution to the original problem

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.

2. Identify a pattern that can be continued as the recursion expands.

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)

Step 2: Identifying the pattern.


• At level j of the recursion, the number of subproblems are now a total of 2j
• Each problem has shrunk in size by factor of 2 “j” time  n/ 2j

Step 3: Summing overall levels of recursion.


• The number of times the input must be halved to reduce the size of n to 2 is
log n
• There are totally “n” levels of recursion  O( n logn)
ANALYSIS
ì 0 if n = 1
ï
T(n) = í 2T(n /2) + n otherwise
ïî sorting both halves merging

T(n) n

T(n/2) T(n/2) 2(n/2)

T(n/4) T(n/4) T(n/4) T(n/4) 4(n/4)


log2n
...
T(n / 2k) 2k (n / 2k)

...

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

T(n) = O(n log n)


T(n) = c. n log n
T(n/2) = c. n/2 log n/2

T(n) = 2T (n/2)+ O(n)


T(n) = 2T (n/2)+ cn
T(n)= 2. c. n/2 log n/2 + cn
T(n) = cn. [logn - 1] + cn
T(n) = cn.logn – cn +cn
T(n) = cn.logn
T(n) =O(nlogn)

You might also like