Factorial Recursion stack Binary Search Towers of Hanoi

Slides:



Advertisements
Similar presentations
Towers of Hanoi Move n (4) disks from pole A to pole C such that a disk is never put on a smaller disk A BC ABC.
Advertisements

Starting Out with Java: From Control Structures through Objects
Introduction to Recursion and Recursive Algorithms
COSC 2006 Data Structures I Recursion III
Recursion CSC 220: Data Structure Winter Introduction A programming technique in which a function calls itself. One of the most effective techniques.
Lesson 19 Recursion CS1 -- John Cole1. Recursion 1. (n) The act of cursing again. 2. see recursion 3. The concept of functions which can call themselves.
CS102 Algorithms and Programming II1 Recursion Recursion is a technique that solves a problem by solving a smaller problem of the same type. A recursive.
Recursion. Binary search example postponed to end of lecture.
Programming with Recursion
1 CSCD 300 Data Structures Recursion. 2 Proof by Induction Introduction only - topic will be covered in detail in CS 320 Prove: N   i = N ( N + 1.
Recursion. 2 CMPS 12B, UC Santa Cruz Solving problems by recursion How can you solve a complex problem? Devise a complex solution Break the complex problem.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
Recursive Algorithms Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Review of Recursion What is a Recursive Method? The need for Auxiliary (or Helper) Methods How Recursive Methods work Tracing of Recursive Methods.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
A Review of Recursion Dr. Jicheng Fu Department of Computer Science University of Central Oklahoma.
Analysis of Algorithm Lecture 3 Recurrence, control structure and few examples (Part 1) Huma Ayub (Assistant Professor) Department of Software Engineering.
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursion Chapter Nature of Recursion t Problems that lend themselves to a recursive solution have the following characteristics: –One or more.
Chapter 2 Recursion: The Mirrors CS Data Structures Mehmet H Gunes Modified from authors’ slides.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 15: Recursion Starting Out with Java: From Control Structures.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 14: Recursion.
Chapter 12 Recursion, Complexity, and Searching and Sorting
CSE 1342 Programming Concepts Recursion. Overview of Recursion nRecursion is present when a function is defined in terms of itself. nThe factorial of.
CIS 068 Welcome to CIS 068 ! Stacks and Recursion.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Chapter 8 Recursion Modified.
Chapter 4 Recursion. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Explain the underlying concepts of recursion.
Recursion Recursion Chapter 12. Outline n What is recursion n Recursive algorithms with simple variables n Recursion and the run-time stack n Recursion.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
By: Lokman Chan Recursive Algorithm Recursion Definition: A function that is define in terms of itself. Goal: Reduce the solution to.
Basic Mathematics Chapter 1 (1.2 and 1.3) Weiss. Recursion / Slide 2 Logarithms * Definition: if and only if * Theorem 1.1: n Proof: apply the definition.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 15 * Recursive Algorithms.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Recursion ITI 1121 N. El Kadri. Reminders about recursion In your 1 st CS course (or its equivalent), you have seen how to use recursion to solve numerical.
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
Recursion ITFN The Stack. A data structure maintained by each program at runtime. Push Pop.
1 Towers of Hanoi Three pegs, one with n disks of decreasing diameter; two other pegs are empty Task: move all disks to the third peg under the following.
Lecture 11 Recursion. A recursive function is a function that calls itself either directly, or indirectly through another function; it is an alternative.
Recursion Powerful Tool
Programming with Recursion
Review of Recursion What is a Recursive Method?
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 19: Recursion.
Chapter 15 Recursion.
Towers of Hanoi Move n (4) disks from pole A to pole C
Chapter 15 Recursion.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Java Software Structures: John Lewis & Joseph Chase
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursion Data Structures.
Recursion Chapter 18.
Review of Recursion What is a Recursive Method?
Chapter 17 Recursion.
Review of Recursion What is a Recursive Method?
Dr. Sampath Jayarathna Cal Poly Pomona
ITEC324 Principle of CS III
Review of Recursion What is a Recursive Method?
Presentation transcript:

Factorial Recursion stack Binary Search Towers of Hanoi Session 05: C# Recursion Factorial Recursion stack Binary Search Towers of Hanoi FEN 2013-03-02 AK IT: Softwarekonstruktion

AK IT: Softwarekonstruktion Recursion In programming languages recursion is when a method is calling it self (recursion may be indirectly) Recursion often comes around when a problem can be solved using a divide and conquer strategy: If the problem is small, we can apply some simple (non-recursive) solution. (called “base case”) Otherwise the problem is divided into smaller sub problems of the same kind. The sub problems are then solved by applying the solution recursively to the sub problems. Eventually the sub problems become so small that the simple solution can be applied, and recursion terminates. When the sub problems are solved, the solutions to the sub problems are combined into a solution to the original problem. FEN 2013-03-02 AK IT: Softwarekonstruktion

Recursion –Divide and Conquer If the problem is small, we can apply some simple (non-recursive) solution (called “base case”). Otherwise the problem is divided into smaller sub problems of the same kind. The sub problems are then solved by applying the solution recursively to the sub problems. Eventually the sub problems become so small that the simple solution can be applied, and recursion terminates. Note the similarities to loops Conquer: Simple sub problems are solved using the non-recursive solution When the sub problems are solved, the solutions to the sub problems are combined into a solution to the original problem. FEN 2013-03-02 AK IT: Softwarekonstruktion

Example n! = n * (n-1)! for n > 0 n! = 1 for n = 0 Many mathematical functions may be defined recursively. For instance, computing the factorial of an number n (n!): n! = n * (n-1)! for n > 0 n! = 1 for n = 0 The base case (simple problem) is when n=0 If n>0 the problem is divided into the subproblem of computing the factorial of n-1 The combine part is multiplying the result of (n-1)! by n. Note: There must be a base case, so recursion eventually stops. FEN 2013-03-02 AK IT: Softwarekonstruktion

Recursive Factorial in C# public static long Fac(long n) { calls++; if (n == 0) return 1; else return n * Fac(n - 1); } FEN 2013-03-02 AK IT: Softwarekonstruktion

Behind the Scenes: The Recursion Stack When a recursive method executes many activations of the method exist at the same time. The virtual machine is handling this by storing the different states of the method on a stack: Value of parameters and local variables Return address When a method is called, an activation is created and pushed onto the stack When a method returns, its activation is popped from the stack The current activation of the method is always the topmost on the stack, and it is the values of parameters, local variables etc. stored that is used. A stack is a list, where insert (push) and remove (pop) are done at the front of the list (stack top). Stack: top FEN 2013-03-02 AK IT: Softwarekonstruktion

AK IT: Softwarekonstruktion Iterative Factorial Actual it is not very smart to compute the factorial of n recursively – a loop can do the job much more efficiently: public long FacIter(int n) { long fac = 1; for (int i = 2; i <= n; i++) fac = fac * i; return fac; } But is it more simple? public long Fac(int n) if (n == 0 || n == 1) return 1; else return n * Fac(n-1); } FEN 2013-03-02 AK IT: Softwarekonstruktion

AK IT: Softwarekonstruktion Exercise Write a recursive method that computes the sum of the first n non-negative numbers. Hint: the sum may be define by: sum(n) = n + sum(n-1) for n > 0 sum(n) = 0 for n = 0 Draw pictures of the recursion stack when sum(3) is computed FEN 2013-03-02 AK IT: Softwarekonstruktion

Binary Search In a sorted random access (array based) data set it is possible to use binary search. Binary search can be formulated very simply using recursion: Strategy: If - the search set is empty Then - the searched element, s, is not in the set Else - inspect the middle element, m - If - m == s - Then - the element is found and we are done - Else - If - m > s - Then - search in the lower half of the set - Else - search in the upper half of the set Note the recursive nature of this solution! FEN 2013-03-02 AK IT: Softwarekonstruktion

AK IT: Softwarekonstruktion In C#… public static bool BinSearch(int l, int h, int x, int[] T) { //PRE T is sorted //Looking for x between l and h in T calls++; int m; if (l > h) return false; else m = (l + h) / 2; if (x == T[m]) return true; if (x > T[m]) return BinSearch(m + 1, h, x, T); return BinSearch(l, m - 1, x, T); } FEN 2013-03-02 AK IT: Softwarekonstruktion

AK IT: Softwarekonstruktion The Towers of Hanoi Three pins: source, S target, T help, H 64 discs with decreasing diameters are to be moved from S to T observing the following rules: A larger disc can not be placed upon a smaller Only one disc can be moved at the time Algorithm? FEN 2013-03-02 AK IT: Softwarekonstruktion

The Towers of Hanoi This yields a recursive solution Solution: Move 63 discs from S to H using T as help Move one disc from S to T Move 63 discs from H to T using S as help Now the problem is how to move the 63 discs. That must be easier: Move 62 discs… Move one disc This yields a recursive solution FEN 2013-03-02 AK IT: Softwarekonstruktion

AK IT: Softwarekonstruktion The Algorithm in C# public static void Hanoi(int n, char s, char h, char d) { //Moves n disks from S(ource) to D(estination) using H(elp) //Do not try this for n much larger 16 calls++; if (n == 1) //System.Console.WriteLine("Move one disk from: " + s + " to:" + d); } else Hanoi(n - 1, s, d, h); Hanoi(n - 1, h, s, d); FEN 2013-03-02 AK IT: Softwarekonstruktion

Efficiency of Recursive Algorithms Overhead in time due to call-return Overhead in space due to the recursion stack The Recursion Tree tells about complexity: The depth tells about memory space The number of nodes tells about running time FEN 2013-03-02 AK IT: Softwarekonstruktion

AK IT: Softwarekonstruktion Examples Draw the recursion trees: Binary Search: O(log n) (time and space) Factorial of n: O(n) (time and space) Towers of Hanoi: O(2n) (time) O(n) (space) FEN 2013-03-02 AK IT: Softwarekonstruktion

Recursive vs. Iterative Algorithms It is always possible to rewrite a recursive algorithm to an equivalent iterative which may be more efficient. But the iterative version is often more complicated, since one has to handle the recursion stack oneself. In some cases it is possible to find iterative algorithms that are more efficient and as simple as the equivalent recursive: Tail recursion: If the recursive call is the last statement in the algorithm, then there is no need for remembering the state of other active calls. The recursion can the be converted to a loop and there is no need for the recursion stack. Hence we get rid of the overhead to call-return and the overhead in space as well. FEN 2013-03-02 AK IT: Softwarekonstruktion