0% found this document useful (0 votes)
140 views43 pages

04 Recursion 4 Labs

Here is the recursive method to print the contents of a folder in a tree format: public static void printFolderContents(File folder) { printIndentation(); System.out.println(folder.getName()); for(File file: folder.listFiles()) { if(file.isFile()) { printIndentation(); System.out.println("- " + file.getName()); } else if(file.isDirectory()) { System.out.println("- " + file.getName()); printFolderContents(file); } } } private static void printIndentation() { System.out.print("| "); } This recursively calls
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
140 views43 pages

04 Recursion 4 Labs

Here is the recursive method to print the contents of a folder in a tree format: public static void printFolderContents(File folder) { printIndentation(); System.out.println(folder.getName()); for(File file: folder.listFiles()) { if(file.isFile()) { printIndentation(); System.out.println("- " + file.getName()); } else if(file.isDirectory()) { System.out.println("- " + file.getName()); printFolderContents(file); } } } private static void printIndentation() { System.out.print("| "); } This recursively calls
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 43

Recursion

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

 LO3.1 Describe the basic ideas of recursion and how to set up


recursive systems that represent certain real-world phenomena.
 LO3.2 Know how to develop recursive algorithms and programs
 LO3.3 Write programs in Java using recursion to solve some
problems, like creating the Fibonacci sequence.
 LO3.4 Analyze a recursive function to find out its’ output
without running.
 LO3.5 Explain type of recursive functions, give examples and
comparing them.
 LO3.6 Compare recursion with iteration, analyze their pros and
cons

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)

F(n) = F(n-1) + F(n-2) // Fibonacci sequence


a(n) = a(n-1)+ d: Arithmetic progression – CS cộng
b(n) = q*b(n-1) // geometric progression- CS nhân

public static int fibo (int n){


if (n<3) return 1;
return fibo(n-1) + fibo(n-2);
}

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

2- Recursion is used to test whether a F(10) =?


value belonging a group or not.

3- Recursion is a another way to


Test whether 34 is an element of
express a loop when number of the Fibo sequence or not?
executions is not known in advance.

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

Example: Sum of an array, named a, having n elements


Sum(a,n) = a[0] + a[1] + … + a[n-2] + a[n-1]
Sum(a, n-1)

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 recursive method Lab 1


includes all
simple
demonstrations

// 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

public static double ap( int n, double a, double d) {


<Code yourself>
}

// Test 1.5 3.5 5.5 7.5 9.5 11.5


System.out.println( ap(6, 1.5, 2 )); //  11.5

13
3- Implementing a recursive method
Lab 1: Demo 4

Compute the nth item of a geometric progression having


the first item a and common multiplier q:
gp (n, a, q) = a , n=1
= gp(n-1, a, q) * q, n>1

public static double gp( int n, double a, double q) {


<Code yourself>
}

// 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

Calculate sum of integral array having n elements


Sum(a,n) = 0 + a[0] + a[1] + …….. + a[n-2] + a[n-1]

Sum(a, n) = 0, n=0;
= Sum(a, n-1) + a[n-1], n>1

public static double sum( double[] a, int n) {


<Code yourself>
}

// 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]

public static int max( double[] a, int n) {


<Code yourself>
}

// 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>
}

// Test : int b[] = { 1, 5, 9, 7, 2, 19,10 };


System.out.println( min(b, 7)); //  1

17
3- Implementing a recursive method
Lab 1: Demo 8
Convert a decimal integer to a b-based numeric string:

n= 35, base=2  100011


“100011” = “10001” + “1”
convert(35,2) = convert(17,2) + digit of 35%2
convert(n,base) = convert(n/base,base) + digit of n%base
Anchor: If n==0 return “0”

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

Tail recursion is characterized by the use of only one recursive


call at the very end of a method implementation.

The last operation is a multiplication.


 It is not a tail recursion

23
4- Classifying Recursive Functions

Based on number of recursive calls: Linear, non-linear recursion.

int factorial ( int n) { int fibo ( int n) {


if (n==1) return 1; if (n<3) return 1;
return n*factorial(n-1); return fibo(n-2) + fibo(n-1);
} }
Two recursive calls
 Binary recursion

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?

This data How to manage a thing?  We need its data.


group is How to manage a running method?  … ?
called as Data of a method:
method’s - Its parameters (data type, value)
Activation - Its return data type
record - Its extra local variables
The function - Return address in its caller
F1() calls the - Dynamic link: Address of its caller activation record
function F2()
Address of the next Address of the caller’s
Data needed
instruction in the caller activation record. It will be
F1(): Caller when the
after the callee the current AR after the
callee runs
F2(): Callee terminates callee terminates

26
5- How to Manage Running Functions?

Activation record in details:

Activation records contain the following:


 Values for all parameters to the method, location of the first
cell if an array is passed or a variable is passed by reference,
and copies of all other data items
 Local (automatic) variables that can be stored elsewhere.
 The return address to resume control by the caller, the address
of the caller’s instruction immediately following the call.
 A dynamic link, which is a pointer to the caller’s activation
record
 The returned value for a method not declared as void

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

f2(), and f2() calls Constants


f3() 1000

All methods use Dynamic links to access constants.


28
6- Anatomy of a Recursive Call

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)

AR of main AR of main AR of main AR of main AR of main AR of main AR of main

29
7- Evaluating Performance of Rec. Methods

Advantage: Natural thinking


Disadvantages:
-So many ARs need to be allocated.
 High memory cost
-So many method calls
 High time cost

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)

AR of main AR of main AR of main AR of main AR of main AR of main AR of main

30
7- Evaluating Performance of Rec. Methods

Disadvantages of Recursive Call:


-So many ARs need to be allocated  High memory cost
-So many method calls High time cost

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

Disadvantages of Recursive Call


- So many ARs need to be allocated  High memory cost
- So many method calls  High time cost

One
operation
must be
performed
many times.

The tree of calls for Fib(6)

32
7- Evaluating Performance of Rec. Methods

Number of addition operations and number of recursive


calls to calculate Fibonacci numbers

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

Loop version, no additive memory is needed.


34
8- Eliminate Tail Recursion
Lab 3: Convert an integer to string numbers.

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

Đệ quy Hồi quy


 Giống nhau giữa đệ quy và hồi quy dưới góc nhìn hiện thực: Hàm
hồi quy cũng gọi chính nó như trong đệ quy nhưng là đệ quy TỚI

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.2 Know how to develop recursive algorithms and programs


 like creating the Fibonacci sequence.
LO3.3 Write programs in Java using recursion to solve some problems,

 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

You might also like