04 Recursion 4 Labs
04 Recursion 4 Labs
Contents
1- Introduction to recursion.
2- Describing a recursive operation.
3- Implementing a recursive method.
4- Classifying recursive functions
5- How to manage running functions?
6- Anatomy of a Recursive Call
7- Evaluating performance of recursive methods.
8- Eliminating recursion
9- Backtracking (15 exercises)
2
Learning Outcomes
3
1- Introduction to Recursion
Definition:
Recursion is a technique in which a concept/an operation is defined by
itself ( đệ: đưa ra, quy: quay về).
Examples
Person = a child of other two persons
n! = n* (n-1)! ( factorial)
4
1- Introduction to Recursion
How to understand Recursion?
We use a reverse deduction (suy diễn ngược) with an initial
data.
Examples:
Person = a child of other two persons
Initial persons: Adam, Eve
1 3 5 7 9 …..
A(n) = 1, n=1
A(n) = A(n-1) + 2, n> 1
1, 1, 2, 3, 5, 8, 13, …
F(n) = 1, n<3
F(n) = F(n-1) + F(n-2)
public static int fibo ( int n){
A recursive method: if (n<3) return 1;
return fibo(n-1) + fibo(n-2);
}
Recursion 5
1- Introduction to Recursion
Where recursion are used?
The Fibonacci sequence:
1- Recursion is used to generate new
elements of a group. n 1 2 3 4
F(n) 1 1 2 3
F(n) = 1, n<=2 public int fiboRec( int n) { public int fiboLoop ( int n) {
= F(n-2)+F(n-1), n>2 if (n<3) return 1; int result =1, t1 =1, t2=1;
return fiboRec(n-2) + fiboRec(n-1); for (int i=3; i<=n; i++) {
result = t1 + t2;
} t1 = t2;
t2= result;
}
return result;
}
Recursion 6
2- Describing a recursive operation
A recursive definition consists of two parts:
The anchor or ground case or base case, the
basic elements that are the building blocks of all
other elements of the set
Rules that allow for the construction of new
objects out of basic elements or objects that have
already been constructed
7
2- Describing a recursive operation
Practice: Recursive expression of numeric sequences
Use the Divide and conquer principle– chia để trị
(1) Write numbers in a line: d1, d2, d3, d4, d5, ………, dn
(2) Some beginning values can be anchors.
(3) Find out relationship next values with previous values
Deduction
Example: Examine the Fibonacci sequence:
1 1 2 3 5 8 13 21 34
Anchors: 1, n<=2
Deductive rule: F(n) = F(n-2) + F(n-1), n>2
Recursion 8
2- Describing a recursive operation
Practice: Recursive expression of operations :
- With recursive methods, there may be more difficulties.
- Use the Divide and conquer principle
- Write the operation in details
- Right side may be anchor
- Left side is the same operation with smaller input
Example: Calculate n!
n! = 1.2.3.4.5.6.…(n-1).n
= (n-1)! . n = n.(n-1)!
Anchors: 1, n<2
Deductive rule: n! = n.(n-1)!
Recursion 9
2- Describing a recursive operation
Practice: Recursive operations on an array
Return 0,n=0
Return a[n-1] + Sum (a, n-1);
Recursion 10
3- Implementing a recursive method
Pseudo-code
n! = 1, n<2
= n* (n-1)!, n>=2
2 lines
// Other test
Để dễ tiếp thu bài học, xin đừng thắc mắc “Hàm đệ quy chạy
như thế nào?”. Câu hỏi này sẽ được trả lời ở phần sau của
chương. Ở đây, chúng ta chú tâm vào cách suy nghĩ đệ quy,
diễn đạt đệ quy và viết hàm đệ quy cho quen đã nhé.
11
3- Implementing a recursive method
Lab1:
Demo 2
Recursive
definitions serve
two purposes:
(1) Generating
new elements
(2)Testing
whether an
element
belongs to a
set
Demo: The
Fibonacci
sequence
12
3- Implementing a recursive method
Lab1: Demo 3
1.5 3.5 5.5 7.5 9.5 11.5
-Compute the nth item of an arithmetic progression
having the first item a and common difference d:
ap(n, a, d) = a, n=1
= ap(n-1, a, d) + d, n>1
13
3- Implementing a recursive method
Lab 1: Demo 4
// Test 1.5 3 6 12 24 48
System.out.println( gp(6, 1.5, 2)); // 48
14
3- Implementing a recursive method
Lab 1: Demo 5
Sum(a, n) = 0, n=0;
= Sum(a, n-1) + a[n-1], n>1
// Test :
double a[] = { 1.5, 2, 4, 5, 2, 6.5 };
System.out.println( sum(a, 6)); // 21
15
3- Implementing a recursive method
Lab 1: Demo 6
Calculate the maximum value in an integral array having n elements
1 5 9 7 2 10 19
max(a, n) := if (n==1) return a[0]
int m= max(a, n-1) // 10
return m>a[n-1]? m : a[n-1]
// Test :
int b[] = { 1, 5, 9, 7, 2, 19,10 };
System.out.println( max(b, 7)); // 19
16
3- Implementing a recursive method
Lab 1: Demo 7
Calculate the minimum value in an integral array
having n elements
min (a,n) = (Do yourself)
public static int min( int[] a, int n) {
<Code yourself>
}
17
3- Implementing a recursive method
Lab 1: Demo 8
Convert a decimal integer to a b-based numeric string:
18
3- Implementing a recursive method
Lab 2: Printing contents of a folder in a tree format:
19
3- Implementing a recursive method
Lab 2: Printing contents of a folder in a tree format:
20
3- Implementing a recursive method
Lab 2: Printing contents of a folder in a tree format:
21
4- Classifying Recursive Functions
Aspect Types
Position where a recursive call Tail/ non-tail | Head/ non-
is put head recursion
Number of recursive calls Linear/ non-linear recursion
Recursive call is easily detected Direct/ indirect recursion
22
4- Classifying Recursive Functions
23
4- Classifying Recursive Functions
24
4- Classifying Recursive Functions
receive(buffer)
Based on
while buffer is not filled up
number of if information is still incoming
functions get a character and store it in
included in buffer;
recursive call: else exit();
Indirect decode(buffer);
recursion.
decode(buffer)
decode information in buffer;
Direct
store(buffer);
recursion
Recursive call is store(buffer)
put in the body transfer information from buffer to file;
of itself receive(buffer);
25
5- How to Manage Running Functions?
26
5- How to Manage Running Functions?
27
5- How to Manage Running Functions?
A demo.
Parameters and Local
variables ( n ) Activation
Dynamic link (4000) record of
= Return Address ( = ) f3(…)
5000 Return value ( int )
Parameters and Local
variables ( n, x ) Activation
Dynamic link (3000) record of
+ Return Address ( + ) f2(…)
Return value ( int )
4000
Parameters and Local
variables (n, k) Activation
Dynamic link (2000)
= record of
Return Address ( = ) f1(…)
3000 Return value ( int )
Parameters and Local
Contents of the run-
variables (args, result) Activation
Dynamic link (1000) record of
time stack when Return Address ( null )
main() calls method main(…)
Return value (void)
f1(), f1() calls 2000
AR of
factorial(1)
AR of AR of AR of
factorial(2) factorial(2) factorial(2)
AR of AR of AR of AR of AR of
factorial(3) factorial(3) factorial(3) factorial(3) factorial(3)
29
7- Evaluating Performance of Rec. Methods
AR of
factorial(1)
AR of AR of AR of
factorial(2) factorial(2) factorial(2)
AR of AR of AR of AR of AR of
factorial(3) factorial(3) factorial(3) factorial(3) factorial(3)
30
7- Evaluating Performance of Rec. Methods
double fact1(int n) {
if (n<2) return 1; fact1(100); // 100 activation records
return n*fact1(n-1);
}
double fact2 (int n) {
double result =1; fact2(100); // 1 activation record
for (int i=2; i<=n; i++)
result *= i;
return result;
}
31
7- Evaluating Performance of Rec. Methods
One
operation
must be
performed
many times.
32
7- Evaluating Performance of Rec. Methods
33
8- Eliminate Tail Recursion
If you can, you should eliminate recursive methods.
How? Use loop statement + Stack for storing data.
An example: Binary Search the target in an sorted array.
Recursive version
35
8- Eliminate Tail Recursion
Lab 3 : Convert an integer to string numbers.
36
Bonus: Backtracking on the 8-queen Problem
Tự đọc nhé: Lab 4
Hồi quy, backtracking, là một kỹ thuật sau khi gán trị cho biến vars[i]
thì đi xem xét gán trị cho biến phía sau vars[i+1] nếu có thể được. Trong
tình huống bị bí thì quay lui lại phần tử trước đó.
Hồi quy một bước (one-step): Khi không thể gán trị cho biến xi thì tìm
trị khác để gán cho biến xi-1
Hồi quy một k bước (k-step): Khi không thể gán trị cho biến xi thì tìm
trị khác để gán cho biến xi-k
Khác biệt giữa đệ quy và hồi quy: Góc nhìn thực thi
37
Bonus: Backtracking on the 8-queen Problem
Tự đọc nhé
38
Bonus: Backtracking on the 8-queen Problem
Tự đọc nhé
39
Bonus: Backtracking on the 8-queen Problem
Tự đọc nhé
40
Bonus: Backtracking on the 8-queen Problem
Tự đọc nhé
41
Summary
LO3.1 Describe the basic ideas of recursion and how to set up recursive
systems that represent certain real-world phenomena.
LO3.4 Analyze a recursive function to find out its’ ouput without running.
them.
LO3.5 Explain type of recursive functions, give examples and comparing
LO3.6 Compare recursion with iteration, analyzes their pros and cons
42
Ôn tập – Viết vào vở
1- Đệ quy là gì?
2- Con người có dùng kỹ thuật đệ quy hay không? Cho hai thí dụ.
3- Làm sao con người hiểu được đệ quy?
4- Tác vụ đệ quy được mô tả như thế nào? Cho thí dụ.
5- Làm sao có được kỹ năng diễn đạt đệ quy?
6- Đệ quy được dùng để làm gì?
7- Đệ quy đuôi là gì?
8- Đệ quy đầu là gì?
9- Đệ quy tuyến tính là gì?
10- Đệ quy phi tuyến là gì?
11- Đệ quy gián tiếp là gì?
12- Đệ quy hỗ tương là gì?
13- Làm sao hệ thống có thể quản lý các hàm đang thực thi?
14- Hãy cho biết activation record của một hàm gồm có những gì cùng với ý nghĩa của từng
thành phần.
15- Tại sao hàm đệ quy khi thực thi lại tốn bộ nhớ?
16- Tại sao hàm đệ quy thực thi lại chậm?
17- Khử đệ quy là gì? Tại sao lại nên khử đệ quy?
18- Khử đệ quy bằng cách nào?
Tìm hiểu thêm:
- Hồi quy là gì?
- Kỹ thuật hồi quy có thể được dùng trong những bài toán nào? Cho ví dụ.
43