CIS 068 Welcome to CIS 068 ! Stacks and Recursion

download CIS 068 Welcome to CIS 068 ! Stacks and Recursion

of 34

  • date post

    13-Jan-2016
  • Category

    Documents

  • view

    227
  • download

    0

Embed Size (px)

Transcript of CIS 068 Welcome to CIS 068 ! Stacks and Recursion

  • Welcome to CIS 068 !

    Stacks and Recursion

  • OverviewSubjects:StacksStructureMethodsStacks and Method CallsRecursionPrincipleRecursion and StacksRecursion vs. IterationExamples

  • Stacks: IntroductionWhat do these tools have in common ?Plate DispenserPEZ Dispenser

  • Stack: PropertiesAnswer:They both provide LIFO (last in first out) Structures123456123456

  • Stacks: PropertiesPossible actions:PUSH an object (e.g. a plate) onto dispenserPOP object out of dispenser

  • Stacks: DefinitionStacks are LIFO structures, providingAdd Item (=PUSH) MethodsRemove Item (=POP) Methods

    They are a simple way to build a collectionNo indexing necessarySize of collection must not be predefined But: extremely reduced accessibility

  • StacksApplication AreasLIFO order is desiredSee JVM-example on next slides...or simply no order is necessaryLab-assignment 5: reading a collection of coordinates to draw

  • Stacks

    Q:How would you implement a Stack ?

  • A look into the JVMSample Code:1 public static void main(String args[ ]){2int a = 3;3int b = timesFive(a);4System.out.println(b+);5}

    6Public int timesFive(int a){7int b = 5; 8int c = a * b;9return (c);10 }

  • A look into the JVMInside the JVM a stack is used to create the local variablesto store the return address from a callto pass the method-parameters

  • A look into the JVM1 public static void main(String args[ ]){2int a = 3;3int b = timesFive(a);4System.out.println(b+);5}

    6Public int timesFive(int a){7int b = 5; 8int c = a * b;9return (c);10 }

    a = 3a = 3bReturn to LINE 3b = 5c = 15

  • A look into the JVM...return (c);...a = 3a = 3bReturn to LINE 3b = 5c = 15 15 a = 3bReturn to LINE 3a = 3bc = 15 Return to LINE 3Temporary storageClear Stack

  • A look into the JVMA look into the JVM1 public static void main(String args[ ]){2int a = 3;3int b = timesFive(a);4System.out.println(b+);5}

    a = 3bc = 15 Temporary storagea = 3b = 15

  • A look into the JVMA look into the JVM1 public static void main(String args[ ]){2int a = 3;3int b = timesFive(a);4System.out.println(b+);5}

    clear stack from local variables

  • A look into the JVMA look into the JVMImportant:

    Every call to a method creates a new set of local variables !

    These Variables are created on the stack and deleted when the method returns

  • Applications using a Stack

    Examples: Finding PalindromesBracket ParsingRPNRECURSION !

  • RecursionRecursion

  • RecursionRecursion

    Sometimes, the best way to solve a problem is by solving a smaller version of the exact same problem first

    Recursion is a technique that solves a problem by solving a smaller problem of the same type

    A procedure that is defined in terms of itself

  • RecursionRecursion

    When you turn that into a program, you end up with functions that call themselves:

    Recursive Functions

  • RecursionRecursion

    public int f(int a){if (a==1) return(1);else return(a * f( a-1));}It computes f! (factorial)Whats behind this function ?

  • FactorialFactorial: a! = 1 * 2 * 3 * ... * (a-1) * aNote:a! = a * (a-1)!remember:...splitting up the problem into a smaller problem of the same type...

    a! a * (a-1)!

  • Tracing the examplepublic int factorial(int a){if (a==0) return(1);else return(a * factorial( a-1));}RECURSION !

  • Watching the Stackpublic int factorial(int a){if (a==1) return(1);else return(a * factorial( a-1));}a = 5a = 5a = 5Return to L4a = 4Return to L4a = 4Return to L4a = 3Return to L4a = 2Return to L4a = 1InitialAfter 1 recursionAfter 4th recursionEvery call to the method creates a new set of local variables !

  • Watching the Stackpublic int factorial(int a){if (a==1) return(1);else return(a * factorial( a-1));}a = 5Return to L4a = 4Return to L4a = 3Return to L4a = 2Return to L4a = 1After 4th recursiona = 5Return to L4a = 4Return to L4a = 3Return to L4a = 2*1 = 2a = 5Return to L4a = 4Return to L4a = 3*2 = 6a = 5Return to L4a = 4*6 = 24a = 5*24 = 120Result

  • Properties of Recursive FunctionsProblems that can be solved by recursion have these characteristics:One or more stopping cases have a simple, nonrecursive solutionThe other cases of the problem can be reduced (using recursion) to problems that are closer to stopping casesEventually the problem can be reduced to only stopping cases, which are relatively easy to solve

    Follow these steps to solve a recursive problem:Try to express the problem as a simpler version of itselfDetermine the stopping casesDetermine the recursive steps

  • SolutionThe recursive algorithms we write generally consist of an if statement:IF the stopping case is reached solve itELSE split the problem into simpler cases using recursion

    Solution on stackSolution on stackSolution on stack

  • Common Programming ErrorRecursion does not terminate properly: Stack Overflow !

  • ExerciseDefine a recursive solution for the following function:

    f(x) = xn

  • Recursion vs. IterationYou could have written the power-function iteratively, i.e. using a loop construction

    Wheres the difference ?

  • Recursion vs. IterationIteration can be used in place of recursionAn iterative algorithm uses a looping constructA recursive algorithm uses a branching structureRecursive solutions are often less efficient, in terms of both time and space, than iterative solutionsRecursion can simplify the solution of a problem, often resulting in shorter, more easily understood source code (Nearly) every recursively defined problem can be solved iteratively iterative optimization can be implemented after recursive design

  • Deciding whether to use a Recursive FunctionWhen the depth of recursive calls is relatively shallow

    The recursive version does about the same amount of work as the nonrecursive version

    The recursive version is shorter and simpler than the nonrecursive solution

  • Examples: Fractal Tree

    http://id.mind.net/~zona/mmts/geometrySection/fractals/tree/treeFractal.html

  • Examples: The 8 Queens Problem

    http://mossie.cs.und.ac.za/~murrellh/javademos/queens/queens.htmlEight queens are to be placed on a chess board in such a way that no queen checks against any other queen

  • Review

    A stack is a simple LIFO datastructure used e.g. by the JVM to create local variable spaces Recursion is a divide and conquer designing technique that often provides a simple algorithmic structure Recursion can be replaced by iteration for reasons of efficiency There is a connection between recursion and the use of stacks There are interesting problems out there that can be solved by recursion