Round and round recursion: the good, the bad, the ugly, the hidden

1 / 46
About This Presentation
Title:

Round and round recursion: the good, the bad, the ugly, the hidden

Description:

cdr = tail (rest of the list) Examples: (car '(a b c)) = a (cdr '(a b c)) = (b c) ... Dragon curve. X - X YF , Y- -FX-Y (start with FX) November 18, 2006 ... –

Number of Views:133
Avg rating:3.0/5.0
Slides: 47
Provided by: troyv7
Category:
Tags: bad | dragon | good | hidden | of | recursion | round | tail | the | ugly

less

Transcript and Presenter's Notes

Title: Round and round recursion: the good, the bad, the ugly, the hidden


1
Round and round recursion the good, the bad,
the ugly, the hidden
  • ACSE 2006 Talk
  • Troy Vasiga
  • Lecturer, University of Waterloo
  • Director, CCC

2
Outline
  • Recursion defined
  • Real-world examples ("The hidden")
  • Benefits ("The good")
  • Examples
  • How it works
  • Pitfalls ("The bad")
  • Larger pitfalls ("The ugly")

3
Recursion Defined
  • See "Recursion"

4
Real Definition
  • Recursion is defining a function/procedure/structu
    re using the function/procedure/structure itself
    in the definition

5
A better definition of Recursion
  • If you still don't understand recursion, see
    "Recursion"

6
A more formal definition
  • A recursive definition will rely on a recursive
    definition and some base case(s)
  • Example define object X of size n using objects
    of type X of size k (1 lt k lt n)

7
Example
  • Babuska (Russian) dolls

8
Real-World Example
  • Shells

9
Real-World Example
  • Flowers

10
Real-World Example
  • Definition of a human
  • I was created by my parents
  • ... who were created by their parents
  • (religious/biological discussion follows)

11
Using Recursion in CS
  • Less code implies less errors
  • Natural way of thinking
  • mathematical
  • inductive reasoning
  • allows both top-down and bottom-up approaches

12
(Linked) Lists
  • C version of linked lists
  • typedef struct list_elem
  • int val
  • struct list_elem next
  • node

13
Recursive Ordered Insert
  • void insert(node head, int newValue)
  • node newNode malloc(sizeof(node))
  • newNode-gtval newValue
  • newNode-gtnext NULL
  • if (head NULL)
  • head newNode
  • else if ((head)-gtnext NULL)
  • (head)-gtnext newNode
  • else if ((head)-gtnext-gtval gt newNode-gtval)
  • newNode-gtnext (head)-gtnext
  • (head)-gtnext newNode
  • else
  • insert((head)-gtnext, newValue)

14
Recursive Length
  • int length(node head)
  • if (head NULL)
  • return 0
  • else
  • return 1length(head-gtnext)

15
Scheme lists
  • In Scheme a list is
  • the empty list () or
  • a head element, followed by a list containing the
    rest of the elements
  • Examples
  • ()
  • (1 2 3 4)
  • ((a b) (c d) (e f))

16
Scheme lists
  • How to access elements from a list?
  • car head
  • cdr tail (rest of the list)
  • Examples
  • (car '(a b c)) gt a
  • (cdr '(a b c)) gt (b c)
  • (car (cdr '(a b c))) gt b
  • (caddr '(a b c)) gt c

17
Length in Scheme
  • (define reclength
  • (lambda (L)
  • (if (eq? L '())
  • 0
  • ( 1 (reclength (cdr L)))
  • )
  • )
  • )

18
Am I right?
  • Prove it!
  • Base case (length '()) gt 0
  • Assume true for list of length k gt 0
  • If length is k1, our algorithm computes
  • 1length(list of size k), which it can do
    correctly.
  • Our algorithm is correct. Q.E.D.

19
Trees
  • Extend linked lists in two dimensions
  • not just "next" but "left" or "right"
  • Definition
  • A tree is
  • empty, or
  • is a node which contains
  • a value
  • a left tree
  • a right tree

20
Binary Search Trees
  • In fact, we will insist the following property is
    also true
  • all nodes in the left subtree of a node are less
    than or equal to the value in the node
  • all nodes in the right subtree of a node are
    greater than the value in the node

21
Picture

10
15
12
23
19
22
Java code
  • public class Node
  • private int value
  • private Node left
  • private Node right
  • // other methods are straightforward

23
Using trees recursively
  • public void insert(Node root, int newValue)
  • if (newValue lt root.getValue())
  • if (root.getLeft() null)
  • root.setLeft(new Node(newValue))
  • else
  • insert(root.getLeft(), newValue)
  • else
  • if (root.getRight() null)
  • root.setRight(new Node(newValue))
  • else
  • insert(root.getRight(), newValue)

24
Inorder traversal
  • public static void inOrder(Node n)
  • if (n ! null)
  • inOrder(n.getLeft())
  • System.out.print(n.getValue()" ")
  • inOrder(n.getRight())

25
Inorder observations
  • Output on original tree
  • 4 6 8 9 10 12 15 19 23
  • Print out "in" the middle
  • What if we change the printing part?
  • Exercise Try to do this without recursion
  • (Answer It is really nasty.)

26
Preorder traversal
  • public void preOrder(Node n)
  • if (n ! null)
  • System.out.print(n.getValue()" ")
  • preOrder(n.getLeft())
  • preOrder(n.getRight())

27
Using traversals
  • Arithmetic expression trees
  • internal nodes are operators
  • leave nodes are operands

28
Using traversals
  • Notice the inorder traversal gives
  • 2 7 - 4 10 / 5
  • Notice the preorder traversal gives
  • - 2 7 4 / 10 5
  • TI, anyone?

29
Recursion always works
  • Theorem Every iterative loop can be rewritten
    as a recursive call

30
How recursion "works"
  • Implicit call stack
  • Every call to a function places an "activation"
    record on top of the stack in RAM
  • Activation record remember the current state
  • Stack is built up, and is empty when we return to
    the main caller

31
Avoiding Recursion is Ugly
  • Consider quicksort
  • Sorts an array into increasing order

32
Recursive Quicksort
  • Recursive
  • void quicksort (int a, int lo, int hi)
  • int ilo, jhi, h
  • int xa(lohi)/2
  • do while (ailtx) i
  • while (ajgtx) j--
  • if (iltj)
  • hai aiaj ajh
  • i j--
  • while (iltj)
  • if (loltj) quicksort(a, lo, j)
  • if (ilthi) quicksort(a, i, hi)

33
Iterative Quicksort
  • QuickSort(A,First,Last)
  • var v,sp,L,L2,p,r,r2
  • sp0
  • Push(First,Last)
  • while( sp gt 0 )
  • Pop(L, r)/2
  • while( L lt r)
  • p (Lr)/2
  • v Ap.key
  • L2 L
  • r2 r
  • while( L2 lt r2 )
  • while( AL2.key lt v )
  • L2 L2L
  • // ...

34
More iterative Quicksort
  • while( Ar2.key gt v )
  • r2 r2-L
  • if(L2 lt r2 )
  • if(L2 equals r2)
  • Swap(AL2,Ar2)
  • L2 L2 L
  • r2 r2 - L
  • // ...

35
Yet more iterative Quicksort
  • if(r2-L gt r-L2)
  • if(Lltr2)
  • Push(L,r2)
  • L L2
  • else
  • if(L2 lt r)
  • Push(L2,r)
  • r r2
  • // end while( L lt r )
  • // end while( spgt0 )
  • // end QuickSort

36
Bad Fibonacci, Bad
  • f(0) 0
  • f(1) 1
  • f(n) f(n-1) f(n-2)

37
Dynamic Programming
  • Recursion leads to a very powerful problem
    solving technique called Dynamic Programming
  • Essentially, don't use the recursive call, but
    write a recurrence relation and solve it from the
    bottom-up

38
Shortest Paths using DP
  • A shortest path is a path between two vertices
    that has minimum weight
  • Number the vertices of the graph from 1..n
  • Let D(k, i, j) mean the shortest path between
    vertices i and j that uses only vertices 1, , k

39
Base case
  • D(0, i, j)
  • 0 if ij
  • w(i,j) if there is an edge (i,j)
  • ? otherwise

40
Recursive case
  • D(k1, i, j) uses either vertex k1 or it doesn't
  • If it doesn't,
  • D(k1, i, j) D(k,i,j)
  • If it does,
  • D(k1, i, j) D(k, i, k1) D(k, k1, j)
  • So, D(k1,i,j) is the minimum of these two

41
Filling in the table
  • In fact, filling in the table is done without
    using recursion
  • As we did in the Fibonacci case, except now, we
    are in more than one dimension

42
Ugly Recursive Main
  • Don't do this in Java
  • public class RecUgly
  • public static int factorial(int n)
  • if (n lt 0)
  • return 1
  • else
  • return nfactorial(n-1)
  • public static void main(String args)
  • System.out.println(factorial(11))

43
Context-Free Grammars
  • Describe very complex things using recursion
  • S -gt (S)
  • S -gt SS
  • S -gt ?

44
Mathematical beauty
  • Koch curves using Lindenmayer systems
  • Let F mean "forward", mean "right" and - mean
    "left"
  • Koch curve
  • Rule F -gt F-FF-F (starting with F)
  • Koch snowflake
  • Start with FFF instead!

45
Dragon curve
  • X -gt XYF, Y-gt-FX-Y (start with FX)

46
Conclusion
  • Recursion is
  • Beautiful
  • Natural (in many senses)
  • Mathematically precise
  • Simple
  • Powerful
  • Recursive
Write a Comment
User Comments (0)
About PowerShow.com