csci 210: Data Structures Recursion

Similar documents
The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015

Mathematical Induction

Functions Recursion. C++ functions. Declare/prototype. Define. Call. int myfunction (int ); int myfunction (int x){ int y = x*x; return y; }

What Is Recursion? Recursion. Binary search example postponed to end of lecture

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

Many algorithms, particularly divide and conquer algorithms, have time complexities which are naturally

Math 55: Discrete Mathematics

Module 2 Stacks and Queues: Abstract Data Types

Near Optimal Solutions

8 Primes and Modular Arithmetic

3. Mathematical Induction

Solving Problems Recursively

Lecture Notes on Linear Search

Lecture 11: Tail Recursion; Continuations

Analysis of Binary Search algorithm and Selection Sort algorithm

Tower Of Hanoi & Reve Puzzles

Pseudo code Tutorial and Exercises Teacher s Version

Recursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., Barnette ND, McQuain WD

Regular Languages and Finite Automata

Algorithms. Margaret M. Fleck. 18 October 2010

GCDs and Relatively Prime Numbers! CSCI 2824, Fall 2014!

Recursion. Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive.

WRITING PROOFS. Christopher Heil Georgia Institute of Technology

Section IV.1: Recursive Algorithms and Recursion Trees

Mathematical Induction. Lecture 10-11

Algorithm Design and Recursion

Recursive Algorithms. Recursion. Motivating Example Factorial Recall the factorial function. { 1 if n = 1 n! = n (n 1)! if n > 1

Recursion and Recursive Backtracking

Collatz Sequence. Fibbonacci Sequence. n is even; Recurrence Relation: a n+1 = a n + a n 1.

CS473 - Algorithms I

CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++

HOMEWORK 5 SOLUTIONS. n!f n (1) lim. ln x n! + xn x. 1 = G n 1 (x). (2) k + 1 n. (n 1)!

SECTION 10-2 Mathematical Induction

CHAPTER 5. Number Theory. 1. Integers and Division. Discussion

PROG0101 Fundamentals of Programming PROG0101 FUNDAMENTALS OF PROGRAMMING. Chapter 3 Algorithms

CHAPTER II THE LIMIT OF A SEQUENCE OF NUMBERS DEFINITION OF THE NUMBER e.

Closest Pair Problem

Assignment 5 - Due Friday March 6

Notes from Week 1: Algorithms for sequential prediction

6.2 Permutations continued

The Prime Numbers. Definition. A prime number is a positive integer with exactly two positive divisors.

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

1. Give the 16 bit signed (twos complement) representation of the following decimal numbers, and convert to hexadecimal:

Patterns in Pascal s Triangle

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

MATHEMATICAL INDUCTION. Mathematical Induction. This is a powerful method to prove properties of positive integers.

IB Maths SL Sequence and Series Practice Problems Mr. W Name

Stack machines The MIPS assembly language A simple source language Stack-machine implementation of the simple language Readings:

Discrete Mathematics and Probability Theory Fall 2009 Satish Rao, David Tse Note 2

Sequential Data Structures

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Lemma 5.2. Let S be a set. (1) Let f and g be two permutations of S. Then the composition of f and g is a permutation of S.

Sample Induction Proofs

Chapter 5. Recursion. Data Structures and Algorithms in Java

Dynamic Programming. Lecture Overview Introduction

The Union-Find Problem Kruskal s algorithm for finding an MST presented us with a problem in data-structure design. As we looked at each edge,

Data Structures and Algorithms Written Examination

Computer Science 210: Data Structures. Searching

Regression Verification: Status Report

Mathematical goals. Starting points. Materials required. Time needed

Handout #1: Mathematical Reasoning

From Last Time: Remove (Delete) Operation

Research Tools & Techniques

MATH 289 PROBLEM SET 4: NUMBER THEORY

Binary Multiplication

In mathematics, it is often important to get a handle on the error term of an approximation. For instance, people will write

Exercises Software Development I. 11 Recursion, Binary (Search) Trees. Towers of Hanoi // Tree Traversal. January 16, 2013

Unit 1 Number Sense. In this unit, students will study repeating decimals, percents, fractions, decimals, and proportions.

Cardinality. The set of all finite strings over the alphabet of lowercase letters is countable. The set of real numbers R is an uncountable set.

Discrete Optimization

CS 103X: Discrete Structures Homework Assignment 3 Solutions

Normal distribution. ) 2 /2σ. 2π σ

We can express this in decimal notation (in contrast to the underline notation we have been using) as follows: b + 90c = c + 10b

Computational Models Lecture 8, Spring 2009

Introduction. Appendix D Mathematical Induction D1

1 The Brownian bridge construction

Creating, Solving, and Graphing Systems of Linear Equations and Linear Inequalities

Math 319 Problem Set #3 Solution 21 February 2002

WHAT ARE MATHEMATICAL PROOFS AND WHY THEY ARE IMPORTANT?

COMPSCI 105 S2 C - Assignment 2 Due date: Friday, 23 rd October 7pm

Computational Geometry. Lecture 1: Introduction and Convex Hulls

What Is Recursion? 5/12/10 1. CMPSC 24: Lecture 13 Recursion. Lecture Plan. Divyakant Agrawal Department of Computer Science UC Santa Barbara

Student Outcomes. Lesson Notes. Classwork. Discussion (10 minutes)

recursion, O(n), linked lists 6/14

CAs and Turing Machines. The Basis for Universal Computation

4/1/2017. PS. Sequences and Series FROM 9.2 AND 9.3 IN THE BOOK AS WELL AS FROM OTHER SOURCES. TODAY IS NATIONAL MANATEE APPRECIATION DAY

Stanford Math Circle: Sunday, May 9, 2010 Square-Triangular Numbers, Pell s Equation, and Continued Fractions

Chapter 6. Cuboids. and. vol(conv(p ))

1 Description of The Simpletron

Discrete Mathematics Problems

An Innocent Investigation

Fibonacci Numbers and Greatest Common Divisors. The Finonacci numbers are the numbers in the sequence 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,...

Fibonacci numbers introduce vectors, functions and recursion.

x a x 2 (1 + x 2 ) n.

Taylor and Maclaurin Series

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

MATH 4330/5330, Fourier Analysis Section 11, The Discrete Fourier Transform

Transcription:

csci 210: Data Structures Recursion

Summary Topics recursion overview simple examples Sierpinski gasket Hanoi towers Blob check READING: GT textbook chapter 3.5

Recursion In general, a method of defining a function in terms of its own definition f (n) = f(n-1) + f(n-2) f(0) = f(1) = 1; In programming, recursion is a call to the same method from a method Why write a method that calls itself? a method to to solve problems by solving easier instance of the same problem Recursive function calls can result in a an infinite loop of calls recursion needs a base-case in order to stop f(0) = f(1) = 1; Recursion (repetitive structure) can be found in nature shape of cells, leaves Recursion is a good problem solving approach Recursive algorithms elegant simple to understand and prove correct easy to implement

Problem solving technique: Divide-and-Conquer break into smaller problems solve sub-problems recursively assemble solutions recursive-algorithm(input) { //base-case if (issmallenough(input)) compute the solution and return it else break input into simpler instances input1, input 2,... solution1 = recursive-algorithm(input1) solution2 = recursive-algorithm(input2)... figure out solution to this problem from solution1, solution2,... return solution }

Problem: write a function that computes the sum of numbers from 1 to n int sum (int n) 1. use a loop 2. recursively

Problem: write a function that computes the sum of numbers from 1 to n int sum (int n) 1. use a loop 2. recursively int sum (int n) { int s = 0; for (int i=0; i<n; i++) s+= i; return s; } int sum (int n) { int s; if (n == 0) return 0; //else s = n + sum(n-1); return s; } How does it work?

return 10 + 45 sum(10) return 9 + 36 sum(9) return 8 + 28 sum(8) return 1+0 sum(1) return 0 sum(0)

Recursion How it works Recursion is no different than a function call The system keeps track of the sequence of method calls that have been started but not finished yet (active calls) order matters Recursion pitfalls miss base-case infinite recursion, stack overflow no convergence solve recursively a problem that is not simpler than the original one

Perspective Recursion leads to compact simple easy-to-understand easy-to-prove-correct solutions Recursion emphasizes thinking about a problem at a high level of abstraction Recursion has an overhead (keep track of all active frames). Modern compilers can often optimize the code and eliminate recursion. First rule of code optimization: Don t optimize it..yet. Unless you write super-duper optimized code, recursion is good Mastering recursion is essential to understanding computation.

Class-work Sierpinski gasket Fill in the code to create this pattern

a b c Towers of Hanoi Consider the following puzzle There are 3 pegs (posts) a, b, c n disks of different sizes each disk has a hole in the middle so that it can fit on any peg at the beginning of the game, all n disks are on peg a, arranged such that the largest is on the bottom, and on top sit the progressively smaller disks, forming a tower Goal: find a set of moves to bring all disks on peg c in the same order, that is, largest on bottom, smallest on top constraints the only allowed type of move is to grab one disk from the top of one peg and drop it on another peg a larger disk can never lie above a smaller disk, at any time PS: the legend says that the world will end when a group of monks, somewhere in a temple, will finish this task with 64 golden disks on 3 diamond pegs. Not known when they started....

Find the set of moves for n=3 a b c a b c

Solving the problem for any n Think recursively Problem: move n disks from A to C using B Can you express the problem in terms of a smaller problem? Subproblem: move n-1 disks from A to C using B

Solving the problem for any n Think recursively Problem: move n disks from A to C using B Can you express the problem in terms of a smaller problem? Subproblem: move n-1 disks from A to C using B Recursive formulation of Towers of Hanoi move n disks from A to C using B move top n-1 disks from A to B move bottom disks from A to C move n-1 disks from B to C using A Correctness How would you go about proving that this is correct?

Hanoi-skeleton.java Look over the skeleton of the Java program to solve the Towers of Hanoi It s supposed to ask you for n and then display the set of moves no graphics finn in the gaps in the method public void move(sourcepeg, storagepeg, destinationpeg)

Correctness Proving recursive solutions correct is related to mathematical induction, a technique of proving that some statement is true for any n induction is known from ancient times (the Greeks) Induction proof: Base case: prove that the statement is true for some small value of n, usually n=1 The induction step: assume that the statement is true for all integers <= n-1. Then prove that this implies that it is true for n. Exercise: try proving by induction that 1 + 2 + 3 +... + n = n (n+1)/2 A recursive solution is similar to an inductive proof; just that instead of inducting from values smaller than n to n, we reduce from n to values smaller than n (think n = input size) the base case is crucial: mathematically, induction does not hold without it; when programming, the lack of a base-case causes an infinite recursion loop proof sketch for Towers of Hanoi: It works correctly for moving one disk (base case). Assume it works correctly for moving n-1 disks. Then we need to argue that it works correctly for moving n disks.

Analysis How close is the end of the world? Let s estimate running time the running time of recursive algorithms is estimated using recurrent functions let T(n) be the time it takes to compute the sequence of moves to move n disks fromont peg to another then based on the algorithm we have T(n) = 2T(n-1) + 1, for any n > 1 T(1) = 1 (the base case) I can be shown by induction that T(n) = 2 n -1 the running time is exponential in n Exercise: 1GHz processor, n = 64 => 2 64 x 10-9 =... a log time; hundreds of years