recursion fib

Post on 14-Apr-2017

187 Views

Category:

Education

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

A recursive lullabyA child couldn't sleep, so her mother told her a story about a little frog, who couldn't sleep, so the frog's mother told her a story about a little bear, who couldn't sleep, so the bear's mother told her a story about a little weasel... who fell asleep. ...and the little bear fell asleep; ...and the little frog fell asleep;...and the child fell asleep.

What’s recursion anyway?

• Can be a applied when a large task can be broken down into smaller repetitive subtasks.

• A programming technique in which a method calls itself.

Fibonacci sequence

• A series of numbers, where the next number is found by adding the two numbers before it.

0, 1, 1, 2, 3, 5, 8, 13, 21……………….

Value of sequence determined by repetitive processing of prior sequence values.

POS 0 1 2 3 4 5 6 7 8

VAL 0 1 1 2 3 5 8 13 21

Recursion and call stack

Fib(5)

Fib(4) + Fib(3)

Fib(3) + Fib(2)

Fib(2) + Fib(1)

Fib(1) + Fib(0)

Fib(5) = Fib(4) + Fib(3) = Fib(3) + Fib(2) + Fib(2) + Fib(1) = Fib(2) + Fib(1) + Fib(1) + Fib(0) + Fib(1) + Fib(0) +…..

Recursion and its needs

Fib(5) = Fib(4) + Fib(3) = Fib(3) + Fib(2) + Fib(2) + Fib(1) = Fib(2) + Fib(1) + Fib(1) + Fib(0) + Fib(1) + Fib(0) +…..

1. Need a base case (when to stop)2. Need to work towards this base case3. Recursive call to call the method itself repeatedly

Fibonacci in Java

public int fibonacci(int n){ return fibonacci(n-1) + fibonacci(n-2);}

public int fibonacci(int n){ if (n <= 1) return n; else return fibonacci(n-1) + fibonacci(n-2); }

New and improved!!

Base Case

Recursive

When to use recursion

• Iterative processes execute until task is done/counter is met. Recursive is preferable when big task can be broken into smaller, repetitive tasks.

• Code is usually less with recursion. Need to identify base cases properly to avoid infinite calls.

Recursion for processing trees

<MOD> <SEC> SECTION A <SEC> SECTION B </SEC> </SEC> <SEC> SECTION C </SEC></MOD>

Tree processing made simple<MOD> <SEC> SECTION A <SEC> SECTION B </SEC> </SEC> <SEC> SECTION C </SEC></MOD>

void processTree(org.w3c.dom.Node node, String dispSeq){ org.w3c.dom.NodeList nl = node.getChildNodes(); StringBuffer dispSeqBuffer; String displaySequence; for (int i = 0; i < nl.getLength() ; i++) { if (nl.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) { dispSeqBuffer = new StringBuffer(); dispSeqBuffer.append(dispSeq); dispSeqBuffer.append("."); dispSeqBuffer.append(i+1); displaySequence = dispSeqBuffer.toString(); dispSeqBuffer = null; //Adding section title and display sequence to a list global to the class titleDispList.add(nl.item(i).getNodeValue(), displaySequence); processTree(nl.item(i), displaySequence); } }}

Did you know?

top related