0% found this document useful (0 votes)
18 views

7 Recursion

The document discusses recursion, including defining arguments for recursive methods, designing recursive algorithms, tracing recursive calls using a run-time stack, examples of recursive algorithms like calculating factorials and finding string lengths, avoiding infinite recursion through base cases, and comparing recursion to iteration.

Uploaded by

Arhaan Khaku
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

7 Recursion

The document discusses recursion, including defining arguments for recursive methods, designing recursive algorithms, tracing recursive calls using a run-time stack, examples of recursive algorithms like calculating factorials and finding string lengths, avoiding infinite recursion through base cases, and comparing recursion to iteration.

Uploaded by

Arhaan Khaku
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

1

COSC 222 Data Structures

Yves Lucet

CC BY-SA 3.0
https://en.wikipedia.org/wiki/Skip_list#/media/File:Skip_list_add_element-en.gif

"Hash table 3 1 1 0 1 0 0 SP" by Jorge Stolfi - Own work. Licensed under CC BY-SA 3.0 via Commons -
https://commons.wikimedia.org/wiki/File:Hash_table_3_1_1_0_1_0_0_SP.svg#/media/File:Hash_table_3_1_1_0_1_0_0_SP.svg
Wk Class Date Activity Reading/Prep given Peer
1 1 Sep 06 Syllabus, TBL, Java review 2
2 Sep 08 Git, testing Java, Generics, Testing
2 3 Sep 13 RAT1: generics; unit testing Complexity
4 Sep 15 Lect: Complexity, streams Lists
3 5 Sep 20 Build & Critic (training) iMAT1
6 Sep 22 tMAT1 Recursion
4 7 Sep 27 RAT2 Stack, Queue P eer 1
8 Sep 29 Build & Critic Iterators
5 9 Oct 04 mini-lecture+exercises iMAT2
10 Oct 06 tMAT2 BST, PQ, heap
6 11 Oct 11 RAT3 Hash, skip list P eer 2
12 Oct 13 Hash table, Skiplist, bottom-up
14.6heap
Shortest
construction
path
7 13 Oct 18 Dijsktra+adaptable PQ Union-find
14 Oct 20 Union-find/Disjoint sets iMAT3
8 15 Oct 25 tMAT3 Search Trees AVL/RB
16 Oct 27 Lecture BST, AVL, (2,4), RB B-Trees P eer 3
9 17 Nov 01 B-trees iMAT4
18 Nov 03 tMAT4
10 19 Nov 08 Midterm review
20 Nov 10 Midterm
11 Nov 15 Reading week
Nov 17 Reading week Text processing
12 21 Nov 22 Pattern matching KMP, BM, Trie
22 Nov 24 RAT4 Huffman coding
13 23 Nov 29 Huffman coding iMAT5
24 Dec 01 tMAT5
14 25 Dec 06 Review/Course Evaluation P eer 4
iPeer evaluation
This Photo by Unknown Author is licensed under
CC BY-SA

• Deadline in iPeer

Events Completion Ratio Due Date


iPeer4 0 of 216 Students Wed, Dec 6, 2023 11:59 pm
iPeer3 0 of 216 Students Wed, Nov 8, 2023 11:59 pm
iPeer2 0 of 216 Students Wed, Oct 11, 2023 11:59 pm
iPeer1 103 of 216 Students Sun, Oct 1, 2023 12:00 am

• Penalty
– 1 day: 20%;
– 2 days: 50%;
– 3+ days: 100%.

3
4

Remember
• It is your job to check your grades weekly; any
mark you do not understand, should be brought to
my attention (or your TA for the lab) asap
• You may receive a 0 for a lab for a number of
reasons: does not compile, not submitted, not
submitted as per the instructions, etc. Check, ask
your TA, and follow instructions.
• Do NOT wait till Christmas!
• And be patient while I go through the backlog of
questions; all emails are stored and will be looked
at.
5

TAs feedback This Photo by Unknown Author is licensed under CC BY-NC

• No code in Git repository


– See the TA for help in uploading
– Check that your code was uploaded by going to the website
• Students renaming their GitHub username
– If the TA does not have your username, you cannot receive a mark
– It is your responsibility to check your marks, and bring any discrepancy (like a
zero for a lab your completed) to the TA for the lab, to me for other grades
• Students
– Asking for zoom meetings with TA
• Go to the lab for help
• Ask questions on zoom
• Come to my office hours
– Asking whether the code is right
• The TA is there to support you by giving you hints and clarifying what you have not
understood.
• The TA will not tell you if the code is right in real time, they need to run the code and do
other verifications to give you a grade.
• Ask precise questions, e.g., why is there a compile error on that line? Could an ArrayList
work?
• Avoid vague questions that show you haven’t spent enough time thinking about it, e.g.,
does that work? [run it] Is that enough testing? [do you have 80% coverage?]
6

RAT
• iRAT2
– 2023: 52%; 2022: 53%; 2018: 59%; 2016: 52%;
2015: 53%
• tRAT2 (to be checked)
– 2023: 80%; 2022: 86%; 2018: 92%; 2016: 89%;
2015: 93%
7

Appeals: all declined


• 6:
– 9 cannot change value of a final variable
• 4: 36, 9, 34. Reread the code carefully
• 6:
– 23: add/remove is O(1) in sets. Set is an interface with several
implementations:
• General purpose: HashSet, TreeSet, and LinkedHashSet
• Special purpose: EnumSet and copyOnWriteArraySet
– 12, 12: storing is not the same as adding
• 8: 2: review stacks
• 10: 28: withdrew
• 11: 17 teams appealed
8

Module 1: Labs

 Unit testing, comparing arrays, sorting


 Coverage testing, counting sort
– [unit/coverage testing expected from now on]
 Streams: Lab 3
9

Practicing
https://cmps-people.ok.ubc.ca/ylucet/DS/Alg
orithms.html
10

Using Recursion

Elsamuko from Kiel, Germany, CC BY-SA 2.0 via Wikimedia Commons

Using Recursion
11

Defining Arguments for Recursion


• Method signature should facilitate recursion.
• May need to use additional parameters
• For example,
– we defined the array reversal method as
ReverseArray(A, i, j), not ReverseArray(A)
– binarySearch(A, i, j, x), not BinarySearch(A, x)
Steps to Design a Recursive
Algorithm
 There must be at least one case (the base case),
for a small value of n, that can be solved directly
 Identify the base case(s) and solve directly

 A problem of a given size n can be reduced to one


or more smaller versions of the same problem
(recursive case(s))
 Devise a strategy to reduce the problem to
smaller versions of itself while making progress
toward the base case
 Combine the solutions to the smaller problems
to solve the larger problem
Recursive Algorithm for Finding the
Length of a String (cont.)
/** Recursive method length
@param str The string
@return The length of the string
*/
public static int length(String str) {
if (str == null || str.equals(""))
return 0;
else
return 1 + length(str.substring(1));
}
Tracing a Recursive Method
 The process of
returning from
recursive calls and
computing the partial
results is called
unwinding the
recursion
Run-Time Stack and Activation
Frames
 Java maintains a run-time stack on which it
saves new information in the form of an
activation frame
 The activation frame contains storage for
 method arguments
 local variables (if any)
 the return address of the instruction that called the
method
 Whenever a new method is called (recursive or
not), Java pushes a new activation frame onto
the run-time stack
Run-Time Stack and Activation
Frames
Factorial of n: n! (cont.)
 The recursive definition can be expressed by the
following algorithm:
if n equals 0
n! is 1
else
n! = n x (n – 1)!
 The last step can be implemented as:
return n * factorial(n – 1);
Factorial of n: n! (cont.)

public static int factorial(int n) {


if (n == 0)
return 1;
else
return n * factorial(n – 1);
}
Infinite Recursion and Stack
Overflow
 If you call method factorial with a negative
argument, the recursion will not terminate because
n will never equal 0
 If a program does not terminate, it will eventually
throw the StackOverflowError exception
 Make sure your recursive methods are constructed
so that a stopping case is always reached
 In the factorial method, you could throw an
IllegalArgumentException if n is
negative
Recursion Versus Iteration
 There are similarities between recursion and iteration
 In iteration, a loop repetition condition determines
whether to repeat the loop body or exit from the loop
 In recursion, the condition usually tests for a base case
 You can always write an iterative solution to a problem
that is solvable by recursion
 A recursive algorithm may be simpler than an iterative
algorithm and thus easier to write, code, debug, and
read
Efficiency of Recursion
 Recursive methods often have slower execution
times relative to their iterative counterparts
 The overhead for loop repetition is smaller than the
overhead for a method call and return
 If it is easier to conceptualize an algorithm using
recursion, then you should code it as a recursive
method
 The reduction in efficiency usually does not
outweigh the advantage of readable code that is
easy to debug
Factorial of n: n! (cont.)
 The recursive definition can be expressed by the
following algorithm:
if n equals 0
n! is 1
else
n! = n x (n – 1)!
 The last step can be implemented as:
return n * factorial(n – 1);
23

Time Complexity
public static int factorial(int n)
if (n == 0)
1. Write recursive equation return 1;
T(n)=T(n-1)+1 else
return n * factorial(n – 1);
T(0)=1 }
2. Solve recursive equation
1. Maple
2. Master’s Theorem
3. Manually (Mathematical proof usually by induction)
24

Master’s Theorem
25
26

What should you be able to do


with recursion?
• Now
– Read recursive algorithms
– Design recursive algorithms
– Implement recursive algorithms
– Debug recursive algorithms

• In the future
– Compute the complexity of recursive
algorithms, at least in the known cases
27

Another Binary Recursive


Method
• Problem: add all the numbers in an integer array A:
Algorithm BinarySum(A, i, n):
Input: An array A and integers i and n
Output: The sum of the n integers in A starting at index i
if n = 1 then return A[i ]
return BinarySum(A, i, n/ 2) + BinarySum(A, i + n/ 2, n/ 2)

• Example trace:

0, 8

0, 4 4, 4
0, 2 2, 2 4, 2 6, 2

0, 1 1, 1 2, 1 3, 1 4, 1 5, 1 6, 1 7, 1

© 2010 Goodrich, Using Recursion


Tamassia
28

Careful
static int[] A = IntStream.rangeClosed(1, 100).toArray();

Recursive Iterative
static int sumRecursive() { static int sumIterative() {
return int sum = 0;
sumRecursiveFromIndexToEnd(0); for (int i=0; i<A.length; i++) {
} sum += A[i];
}
return sum;
static int
}
sumRecursiveFromIndexToEnd(int
i) {
if (i==A.length - 1) return A[i];
else return A[i] + static int sumStream() {
sumRecursiveFromIndexToEnd(i+1); return Arrays.stream(A).sum();
} }

Time: O(n) Time: O(n)


Space: O(n) in addition to array Space: O(1) in addition to array
29

Depth-first search
• Visit all nodes in a graph

DFS-recursive(G, s):
mark s as visited
for all neighbours w of s in Graph G:
if w is not visited:
DFS-recursive(G, w)
https://www.hackerearth.com/practice/algorithms/graphs/depth-first-search/tutorial/

https://cmps-people.ok.ubc.ca/ylucet/DS/DFS.html
30

APPLICATION EXERCISE
31

Application:
inteDashboard
• Application exercise: Recursion
1. Write your code
2. Look at other people code
32

Code & Read Practice


• Write a short recursive Java method that
rearranges an array of integer values so that
all the even values appear before all the odd
values.
– Write your solution
– Write unit tests
– Write the complexity of your algorithm
(time/space)
1. Write solution on inteDashboard
2. Comment other teams solutions in
inteDashboard
33

eGallery
34

Solution
Official solution
35

public class Rearrange {


static void organize(int[] data, int low, int high) {
if (low < high) {
if ((data[high] & 1) == 0) {//even
int temp = data[high];
data[high] = data[low];
data[low] = temp;
organize(data, low+1, high);//data[low] is known to be even
} else {
organize(data, low, high-1);//data[high] is known to be odd
}
}
} class RearrangeTest {
@Test
void testOrganize() {
int[] A = {5, 4, 7, 3, 6, 2};
Rearrange.organize(A, 0, A.length-1);
int[] B = {2, 6, 4, 3, 7, 5};
Assert.assertArrayEquals("Arrays not equal", B, A);
}
}
36

Readings
Do not forget
• your readings
• iPeer
37

Questions?

This Photo by Unknown Author is licensed under


CC BY
38

End of class This Photo by Unknown Author is licensed under CC BY

You might also like