2a Recursive Functions I
2a Recursive Functions I
Functions I
Sample Algorithm 1
Input: An array, list, containing n elements
Output: Sorted Array in ascending order
Associated Structure: None
Begin Proc
Repeat for i = 1 to N Step 1
Set current := i
Repeat for location = i to N step 1
If list [location] < list [current]
// min element identified
Set current := location
End if
End Repeat
If ( i <> current)// if swap required
swap ( list [i], list [current] )
End if
End Repeat
End
2
Growth Factors for Algorithm 1
3
Sample Procedure 2
4
Growth Factor for MergeSort
Recursive Procedure
Starts withn elements
Reduces array by half in each recursion
Makes two recursive calls each time
Processes all elements once each time
5
Analysis of Recursive Procedures
T(n) cn
7
Recursion Tree
T(n) = 2T(n/2) + cn
T(n) cn
8
Recursion Tree
T(n) = 2T(n/2) + cn
T(n) cn
9
Recursion Tree
T(n) = 2T(n/2) + cn
T(n) cn
T(n/8) c(8*n/8)
10
Recursion Tree
T(n) = 2T(n/2) + cn
T(n) cn
T(n/8) c(8*n/8)
. . . . . . . . . . .
T(1)
11
Recursion Tree
T(n) = 2T(n/2) + cn
T(n) cn
T(n/8) c(8*n/8)
. . . . . . . . . . .
T(1) c(n*1)
12
Analysis of Recursive Tree
13
Analysis of Recursive Tree
14
Analysis of Recursive Tree
T(n) cn2
16
Recursion Tree 2
T(n) = 2T(n/2) + cn2
T(n) cn2
17
Recursion Tree 2
T(n) = 2T(n/2) + cn2
T(n) cn2
18
Recursion Tree 2
T(n) = 2T(n/2) + cn2
T(n) cn2
T(n/8) c(8(n/8)2)
19
Analysis of Recursive Tree 2
20
Recursion Tree 3
T(n) = 4T(n/2) + cn
T(n) cn
21
Recursion Tree 3
T(n) = 4T(n/2) + cn
T(n) cn
T(n/2) c(4*(n/2))
22
Recursion Tree 3
T(n) = 4T(n/2) + cn
T(n) cn
T(n/2) c(4*(n/2))
. . . c(16*(n/4))
T(n/4)
T(n/8) . . . . . . c(64*(n/8))
. . . . . . . . . . .
T(1) c(?)
23
Analysis of Recursive Tree 3
24
Analysis of Recursive Tree 3
27