Recursion.

Slides:



Advertisements
Similar presentations
CS1010: Programming Methodology
Advertisements

Towers of Hanoi
2.3 Recursion do automated demo of towers of hanoi before class
Factorial Recursion stack Binary Search Towers of Hanoi
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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 14: Recursion by.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 1 What comes next? Recursion (Chapter 15) Recursive Data Structures.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L10 (Chapter 19) Recursion.
Review of Recursion What is a Recursive Method? The need for Auxiliary (or Helper) Methods How Recursive Methods work Tracing of Recursive Methods.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
15-1 Chapter-18: Recursive Methods –Introduction to Recursion –Solving Problems with Recursion –Examples of Recursive Methods.
Chapter 15: Advanced Topics: Introducing Data Structures and Recursion Visual Basic.NET Programming: From Problem Analysis to Program Design.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
# 1# 1 VBA Recursion What is the “base case”? What is the programming stack? CS 105 Spring 2010.
Chapter 8 Recursion Modified.
Recursion Recursion Chapter 12. Outline n What is recursion n Recursive algorithms with simple variables n Recursion and the run-time stack n Recursion.
Data Structures & Algorithms Recursion and Trees Richard Newman.
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.
Pass the Buck Every good programmer is lazy, arrogant, and impatient. In the game “Pass the Buck” you try to do as little work as possible, by making your.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Towers of Hanoi Move n (4) disks from pole A to pole B such that a larger disk is never put on a smaller disk A BC ABC.
UNIT 17 Recursion: Towers of Hanoi.
Tower of Hanoi Tower of Hanoi is a mathematical puzzle invented by a French Mathematician Edouard Lucas in The game starts by having few discs stacked.
Recursion by Ender Ozcan. Recursion in computing Recursion in computer programming defines a function in terms of itself. Recursion in computer programming.
Lecture 11 Recursion. A recursive function is a function that calls itself either directly, or indirectly through another function; it is an alternative.
Recursion Chapter 10 Carrano, Data Structures and Abstractions with Java, Second Edition, (c) 2007 Pearson Education, Inc. All rights reserved X.
Recursion Chapter 10 Slides by Steve Armstrong LeTourneau University Longview, TX  2007,  Prentice Hall.
Review of Recursion What is a Recursive Method?
Recursion.
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 19: Recursion.
Chapter 15 Recursion.
Subject Name: Design and Analysis of Algorithm Subject Code: 10CS43
Decrease-and-Conquer Approach
Chapter 15 Recursion.
Introduction to Recurrence Relations
Chapter 19 Recursion.
Chapter 7 Sorting Spring 14
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Chapter 8: Recursion Java Software Solutions
Java Software Structures: John Lewis & Joseph Chase
Divide and Conquer – and an Example QuickSort
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursive Definitions
Algorithm Analysis (for Divide-and-Conquer problems)
Chapter 12 Recursion (methods calling themselves)
2.3 Recursion do automated demo of towers of hanoi before class
Data Structures & Algorithms
Chapter 14: Recursion Starting Out with C++ Early Objects
Unit-2 Divide and Conquer
Chapter 5 Divide and Conquer
Chapter 8: Recursion Java Software Solutions
Review of Recursion What is a Recursive Method?
Recursive GCD Demo public class Euclid {
The Hanoi Tower Problem
Chapter 8: Recursion Java Software Solutions
Chapter 18 Recursion.
CSE 373 Data Structures and Algorithms
Review of Recursion What is a Recursive Method?
Dr. Sampath Jayarathna Cal Poly Pomona
Recursion Chapter 12.
2.3 Recursion Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2002–2010 · 2/17/11.
Algorithms and data structures: basic definitions
Review of Recursion What is a Recursive Method?
Presentation transcript:

Recursion

Recursion What is recursion? When one function calls itself directly or indirectly. Gcd. Find largest integer d that evenly divides into p and q. base case reduction step, converges to base case 1) What is your first impression of this code? public static int gcd(int p, int q) { if (q == 0) return p; else return gcd(q, p % q); } base case reduction step

H-tree Used in integrated circuits to distribute the clock signal. H-tree of order n. Draw an H. Recursively draw 4 H-trees of order n-1, one connected to each tip. and half the size tip Application: distribute clock signal to endpoints on integrated circuit. Want distance from clock to each endpoint to be the same. Otherwise clock skew. size order 1 order 2 order 3

Htree in Java public class Htree { public static void draw(int n, double sz, double x, double y) { if (n == 0) return; double x0 = x - sz/2, x1 = x + sz/2; double y0 = y - sz/2, y1 = y + sz/2; StdDraw.line(x0, y, x1, y); StdDraw.line(x0, y0, x0, y1); StdDraw.line(x1, y0, x1, y1); draw(n-1, sz/2, x0, y0); draw(n-1, sz/2, x0, y1); draw(n-1, sz/2, x1, y0); draw(n-1, sz/2, x1, y1); } public static void main(String[] args) { int n = Integer.parseInt(args[0]); draw(n, .5, .5, .5); draw the H, centered on (x, y) What is the computational cost of running this program? recursively draw 4 half-size Hs

Computational Cost of the H-Tree Program H-tree of Order 1 5 calls to draw() = 41 + 40 H-tree of Order 2 21 calls to draw() = 42 + 41 + 40 H-tree of Order 3 85 calls to draw() = 43 + 42 + 41 + 40 Execution time grows exponentially

Towers of Hanoi http://en.wikipedia.org/wiki/Image:Hanoiklein.jpg

Towers of Hanoi Move all the discs from the leftmost peg to the rightmost one. Only one disc may be moved at a time. A disc can be placed either on empty peg or on top of a larger disc. Edouard Lucas invented Towers of Hanoi puzzle (1883) Lucas died as the result of a freak accident at a banquet when a plate was dropped and a piece flew up and cut his cheek. He died of erysipelas (rare skin infection) a few days later. start finish Towers of Hanoi demo Edouard Lucas (1883)

Towers of Hanoi: Recursive Solution Move n-1 smallest discs right. Move largest disc left. cyclic wrap-around Consider the task of moving n discs from leftmost pole to rightmost pole. It is definitely the case that you need to transfer the biggest disc to the bottom of the rightmost pole, but you can't do that until all the remaining n-1 discs are removed from pole A. To get them out of the way, a good place to store them would be the middle pole. Once you have done this, you move the largest disc to pole C, and then transfer the rest of the discs from pole B to pole C. Move n-1 smallest discs right.

Implementing the Recursive Solution Discs 1…n: 1 is the smallest disc, n is the largest moves(int n, boolean left): moves(n, true): Moves discs 1…n one pole to the left moves(n, false): Move discs 1…n one pole to the right

Towers of Hanoi: Recursive Solution Dr. Java Demo public class TowersOfHanoi { public static void moves(int n, boolean left) { if (n == 0) return; //base case moves(n-1, !left); //move n-1 discs to right if (left) System.out.println(n + " left"); else System.out.println(n + " right"); } public static void main(String[] args) { int N = Integer.parseInt(args[0]); moves(N, true); moves(n, true) : move discs 1 to n one pole to the left moves(n, false): move discs 1 to n one pole to the right smallest disc

Recursive Function Call Tree On the Board

Computational Cost of Towers of Hanoi T(n) = Number of moves required for moving n disks T(1) = 1 T(n) = 2*T(n-1) + 1 Recurrence Relation

Computational Cost of Towers of Hanoi T(n) = 2*T(n-1)+1; T(1) = 1 2 Discs; T(2) = 3 moves 3 Discs; T(3) = 7 moves 4 Discs; T(4) = 15 moves What is a closed-form expression for n discs? n Discs: T(n) = 2n -1 Execution time grows exponentially

So What if Time Grows Exponentially? Assume that it takes 1 second to make a single move: 1 disc: 21-1 = 1 second 10 discs: 210-1 seconds ~ 17 minutes 20 discs: 220-1 seconds ~ 12 days 30 discs: 230-1 seconds ~ 34 years! Algorithms with exponential running times are no match even for the fastest computers for large values of n Can we implement a non-recursive solution?

Outputs of the Recursive Solution % java TowersOfHanoi 3 1 left 2 right 3 left % java TowersOfHanoi 4 1 right 2 left 3 right 4 left every other move is smallest disc Every other move is the smallest disc The smallest disc moves in the same direction There are 2^n-1 moves total Need to make a total of 2n -1 moves

Many important problems succumb to divide-and-conquer. Divide-and-conquer paradigm. Break up problem into smaller subproblems of same structure. Solve subproblems recursively using same method. Combine results to produce solution to original problem. Many important problems succumb to divide-and-conquer. FFT for signal processing. Parsers for programming languages. Multigrid methods for solving PDEs. Quicksort and mergesort for sorting. Hilbert curve for domain decomposition. Quad-tree for efficient N-body simulation. Midpoint displacement method for fractional Brownian motion. Divide et impera. Veni, vidi, vici. - Julius Caesar "Divide and conquer", Caesar's other famous quote "I came, I saw, I conquered" Divide-and-conquer idea dates back to Julius Caesar . (100 BCE - 44 BCE). Favorite war tactic was to divide an opposing army in two halves, and then assault one half with his entire force. Integer arithmetic for RSA cryptography. Adaptive quadrature for integration.

Summary How to write simple recursive programs? Base case, reduction step. Trace the execution of a recursive program. Use pictures. Why learn recursion? New mode of thinking. Powerful programming tool. Divide-and-conquer. Elegant solution to many important problems. Towers of Hanoi = recursive music

Homework 4

Eureka!

Two approaches Random (“generate-and-test”) Recursive