Chapter 4 - Recursion
Chapter 4 - Recursion
return tinh(n-1) + 5
Do yourself
• Find a recursive definition of the function/sequence:
1. a[n] = an = n, n =1, 2, 3, …
2. f[n] = f(n) = 1 + 2 + 3 + … + n, n = 1, 2, 3, …
f(n) = 1 + 2 + 3 + … + n, n = 1, 2,
• f(n) = 1+2 + … + (n-1) + n
• f(n-1) = 1+2 + … + (n-1)
f(n) = f(n-1) + n, if n > 1
and f(1) = 1
procedure tinhf(n: positive integer)
if n = 1
return 1
else
return tinhf(n-1) + n
What is S?
S = {10, 1100, 111000, …}
Do yourself
Define the sets recursively
Ex. A = {3, 6, 9, …}
• 3A
• B = {4, 12, 36, 108, …} • x A x +3 A
• C = {1,1/3,1/9,1/27,…}
• S = {100, 110000, 111000000, 111100000000,
…}
Ex. S = {10, 1100, 111000, …}
• 10 S
• w A 1w0 A
The merge sort - idea
mergesort(4,7,2,6,9,3,1,8,5)
4 7 2 6 9 3 1 8 5
mergesort(4,7,2,6) mergesort(9,3,1,8,5)
return 2 4 6 7 return 1 3 5 8 9
merge(2 4 6 7 and 1 3 5 8 9)
return 1 2 3 4 5 6 7 8 9 sorted
472893165
4728 93165
47 2 8 93 165
4 7 2 8 9 3 1 6 5
6 5
6 5
4 7 2 8 9 3 1 5 6
47 2 8 39 156
2478 13569
1 2 3 4 5 6 7 8 9
The Merge Sort Algorithm
procedure mergesort(L = a1,...,an)
if n> 1 then
m := floor(n/2)
recursively
L1 := a1,a2,...,am
L2 := am+1,am+2,...,an
L := merge(mergesort(L1),mergesort(L2))
{L is now sorted}
L:
How to merge?
procedure merge(L1,L2: sorted lists)
L := empty list
while L1 and L2 are both nonempty
remove smaller of first elements of L1
and L2 from its list; put it at the right end of
L
if one list is empty then
remove all elements from the other list and
append them to L
return L {merged}
pseudocode
procedure merge(l1, l2: increasing order)
n := length(l1) m := length(l2)
O(n+m)
i := 1 j := 1 k := 1
while (i n & j m ) # both l1 and l2 are not empty
if (l1[i] < l2[j]) # compare
l[k] := l1[i] # remove the smaller one, put it in l[ ]
i := i+1 # update the smallest of l1
else
l[k] := l2[j] # remove the smaller one, put it in l[ ]
j := j+1 # update the smallest of l2
k := k+1
while (i n ) # if l1 is not empty,
l[k] := l1[i] # append all elements of l1 to l[ ]
i := i+1 k := k+1
while (j m) # if l2 is not empty,
l[k] := l2[j] # append all elements of l2 to l[ ]
j := j+1 k := k+1
return(l) {l is the final sorted list}
Recursion and Iteration
• Basis step:
“1 = 1(1+1)/2” true ?
easy
P(1) is true
• So
1+2+3+…+k+(k+1) = k(k+1)/2 + (k+1)
?
Do some
math
skills
= [k(k+1)+ 2(k+1)]/2
= (k+1)(k+2)/2
P(k+1)
Proved.
1/ Prove that 2n < n!, for integer n 4 using induction.