Title: ECE 242 Spring 2003 Data Structures in Java
1ECE 242 Spring 2003Data Structures in Java
- http//rio.ecs.umass.edu/ece242
- Recursion
- Prof. Lixin Gao
2Todays Topics
- Introduction to recursion
- How recursion works
- Some examples
3Summation
- 12345100
- Sum(100) 123100
- 12 99 100
- sum (99) 100
- sum(n) sum (n-1) n
- sum(0) 0
Recursion step
Base step
4Summation Method
- int sum(int n)
- //base step
- if( nlt0 )
- System.out.println(Only positive integers.)
- return 1
-
- else if(n 0)
- return 0
- //recursive step
- int temp n sum (n-1)
- return temp
5Factorial
- 4! 4 3 2 1
- n! n (n-1) 1
- 4! 4 3!
- n! n (n-1)!
- factorial(n) n factorial(n-1)//recursive step
- factorial(1) 1 //base step
6Method Factorial
- // Assume n is a positive integer.
- int fact(int n)
- //base step
- if (n 1)
- return 1
- //recursive step
- int temp n fact(n-1)
- return temp
-
7Iteration
- Seen in almost all the programs
- When processing a large number of related tasks
- for
- while loop
- dowhile
8Recursion
- A close sibling of iteration
- Instead of a loop structure, a method that calls
itself or partially defined by itself.
9A Recursive Method Invokes Itself
sum(n) sum (n-1) n sum(0) 0
n! n (n-1)! 1! 1
10Recursion
- Duplicate itself but with different parameters
- Reduce a complex problem into a smaller one
- Divide and conquer
11Recursion
- Define an object in terms of itself
- Consists of two parts
- Recursive step
- Base step
f(n) f(n-1) n f(1) 1
12Method Factorial
- int fact(int n)
- //base step
- if (n 1)
- return 1
- //recursive step
- int temp n fact(n-1)
- return temp
-
13Method Factorial (Cont.)
fact(4) temp ?, n4
fact(3) temp ?, n3
fact(2) temp?, n2
fact(1) return 1
temp2 return 2
temp6 return 6
temp24 return 24 4! 24
14Fibonacci Numbers
- 0, 1, 1, 2, 3, 5, 8, 13,
- Fib(n) Fib(n-1) Fib(n-2)
- Fib(0) 0
- Fib(1) 1
Recursive case
Base case
15Iterative Implementation of Fibonacci Numbers
- int Fib(int n)
- int fib11,fib00, fibn, i
- if(nlt1)
- return n
- else
- for(i2iltni)
- fibnfib1fib0
- fib0fib1
- fib1fibn
-
- return fibn
-
16Recursive Implementation of Fibonacci Numbers
- int Fib(int n)
- if(nlt1)
- return n
- else
- return (Fib(n-1)Fib(n-2))
5
Fib(5)
2
3
Fib(3)
Fib(4)
1
2
1
1
Fib(1)
Fib(2)
Fib(2)
Fib(3)
0
1
1
1
0
1
Fib(2)
Fib(1)
Fib(1)
Fib(0)
Fib(1)
Fib(0)
0
1
Fib(1)
Fib(0)
17Print A Linked List Recursively
head
node1
node2
node3
print the rest of the list
print the first node
18Code To Print A Linked List Recursively
- public void printListRec(Node head)
- if(isEmpty(head) )
- return
- else
- //print the first node
- System.out.println(head.value)
- //print the rest of the list
- printListRec(head.next)
-
19Stack For Calling Method
- public methodA(int argA)
- int x, y
- methodB(y)
- return x
-
- public methodB(int argB)
- int i, j
- return i
-
Instruction pointer (IP)
20Calling Stack
push in
- public methodA(int argA)
- int x, y
- methodB(y)
-
- public methodB(int argB)
- int i, j
- return i
-
Instruction pointer (IP)
x, y
Stack frame of methodA
IP
argA
stack
21Calling Stack Of Recursive Call
- int fact(int n)
- if(nlt0)
- return 1
- else
- return (fact(n-1)n)
-
-
Calling stack
fact(n-1)
fact(n)
22Calling Stack
- int fact(int n)
- //base step
- if (n 1)
- return 1
- //recursive step
- int temp n fact(n-1)
- return temp
-
- fact(4) 4! 24
Calling stack
temp1
fact(0)
n0
temp?
temp1
fact(1)
n1
temp?
temp2
fact(2)
n2
temp?
temp6
fact(3)
n3
temp24
temp?
fact(4)
n4
23What Does Mystery Do?
- void mystery(int level)
- int i
- if(level lt3)
- for(i0iltleveli) System.out.print( )
- System.out.println(Enter mystery at level
level) - for(i0iltleveli) System.out.print( )
- System.out.println(I work on level level
problem) - mystery(level1)
- for(i0iltleveli) System.out.print( )
- System.out.println(Exit mystery at level
level) -
24Mystery Output
- Enter mystery at level1
- I work on level1 problem
- Enter mystery at level2
- I work on level2 problem
- Enter mystery at level3
- I work on level3 problem
- Exit mystery at level 3
- Exit mystery at level 2
- Exit mystery at level 1
25Why Recursive Solutions?
- It is natural to solve some problems recursively
- Fibonacci Numbers
- Hanoi Tower
- MergeSort
26Tower Of Hanoi
- Goal Move all disks from A to C
- Rule
- No bigger disk is on top of smaller disk at any
time - Move one disk at a time
C
B
A
4 disks
27Tower Of Hanoi
- 1 disk moves from A to C Simple!
- 2 disks move from A to C
C
B
A
3
1
2
2 disks
28N disks from A to C?
- Move n-1 disks from A to B
- Move disk n from A to C
- Move n-1 disks from B to C
3
1
C
B
A
n-1 disks
2
disk n
29Recursive Code For Hanoi Tower
- void move(int n, char start, char finish, char
buf) - if(n1)
- System.out.println(Move fromstart
tofinish) - else
- move(n-1,start,buf,finish)
- System.out.println(Move fromstart
tofinish) - move(n-1,buf,finish,start)
-
30Trace Of Recursive Hanoi Tower (Example of 3
disks)
- move(3, A, C, B)
- move(2, A, B, C)
- move(1, A, C, B)
- move from A to C
- move from A to B
- move(1, C, B, A)
- move from C to B
- move from A to C
- move(2, B,C, A )
- move(1, B, A, C)
- move from B to A
- move B to C
- move(1, A, C, B)
- move from A to C
- End of 1
- End of 2
- End of 3
314-disk Example
C
B
A
324-disk Example
C
B
A
334-disk Example
C
B
A
34Demo Of Hanoi
- A nice animation of Hanoi online
- http//www.mazeworks.com/hanoi/index.htm
35Sorting
- Sorting algorithms
- Selection Sort
- Insertion Sort
- Both algorithms are of O(N2)
- Another Sorting algorithm MergeSort
36Recursive MergeSort
- Divide and Conquer MergeSort
- Divide Split the list into two or more equal
sub-lists - Recursion Sort each sub-list using a recursive
call - Conquer Merge the sorted sub-lists into a
solution for the original problem
37MergeSort Split
38MergSort Join
39Recursive Merging
- S1, S2 are sorted sub-sequences
5
3
S1
8
2
S2
Temp buffer
5
3
8
2
40MergeSort Needs Extra Storage
- Unlike selection sort, merge sort does not work
in place - A temporary collection is needed so twice as much
memory is required.
41Code For MSort
- public class Msort
- public static void main(String args)
- //data to be sorted.
- int data 54, 45, 32, 20, 21, 12,
14, 8, 9, 4, 0, 3 - //print out the original data
- System.out.print (" ")
- for(int i 0 i lt data.length i)
- System.out.print(datai" ")
- System.out.println(" ")
- //call sorting method to sort the data
- sorting( data )
42Code For MSort (Cont.)
- System.out.println("")
- //after sorting, print out the sorted array.
- System.out.print(" ")
- for(int i 0 i lt data.length i)
- System.out.print(datai" ")
- System.out.println(" ")
-
43sorting Method
- static void sorting( int data)
-
- int start 0
- int end data.length-1
- // call mergeSort(...)
- mergeSort(data, start, end)
-
44Code For mergeSort
- static void mergeSort(int data, int start,
int end) - // if start gt end, means the sub-array is
already sorted. - if( start lt end)
- //calculate the middle of the array and split it
into two halves. - int mid (startend)/2
- //recursively sort the first half
- mergeSort(data, start, mid)
- //recursively sort the second half
- mergeSort(data, mid1, end)
- //merge the two sorted half-array together.
- merge(data, start, mid, end)
-
-
45Code For merge
- private static void merge(int data, int
start, int mid, int end) -
- //firstCopied number of elements copied in the
first half arrray - //secondCopied number of elements copied in the
second half array. - int firstCopied 0, secondCopied 0
- int length end-start 1, index 0
- int temp new intend-start 1
- //size of the first half array
- int firstSize mid-start1
- //size of the second half array
- int secondSize end-mid
46Code For merge (Cont.)
- //while both half arrays still have elements
remain - while(firstCopied lt firstSize secondCopied lt
secondSize) - //compare which element is smaller, and copy
that element to the buffer - if (datastartfirstCopied lt
datamid1secondCopied) -
- temp index
datastartfirstCopied - firstCopied
-
- else
-
- tempindex
datamid1secondCopied - secondCopied
-
-
47Code For merge (Cont.)
- //copy the remains of either the first array
or the second array - while(firstCopied lt firstSize)
- temp index datastartfirstCopie
d - firstCopied
-
- while(secondCopied lt secondSize)
- tempindex datamid1secondCopie
d - secondCopied
-
- //copy the sorted elements from the buffer
back to the original array - for(int i0 iltend-start1 i)
- datastartitempi
-
48Complexity Of MergeSort
- Each round of Merging needs N comparisons
- There are log2N round of merging
- Average number of comparison is about O(NlogN)
for an array of size N
49Link To The Sorting Demo
- A set of sorting algorithm demos
- Merge Sort
50Code For MergeSort