CS102 – Recursion David Davenport Bilkent University Ankara – Turkey Spring 2003.

Slides:



Advertisements
Similar presentations
Recursion.
Advertisements

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.
Recursion Chapter 14. Overview Base case and general case of recursion. A recursion is a method that calls itself. That simplifies the problem. The simpler.
Recursion.  Understand how the Fibonacci series is generated  Recursive Algorithms  Write simple recursive algorithms  Analyze simple recursive algorithms.
Recursion Ellen Walker CPSC 201 Data Structures Hiram College.
ITEC200 – Week07 Recursion. 2 Learning Objectives – Week07 Recursion (Ch 07) Students can: Design recursive algorithms to solve.
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.
Recursion Chapter 7. Spring 2010CS 2252 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn how.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 19 Recursion.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 1 What comes next? Recursion (Chapter 15) Recursive Data Structures.
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.
Fall 2007CS 2251 Recursion Chapter 7. Fall 2007CS 2252 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method.
Chapter 15 Recursive Algorithms. 2 Recursion Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 20 Recursion.
Recursion.  Identify recursive algorithms  Write simple recursive algorithms  Understand recursive function calling  With reference to the call stack.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Recursion.
Introduction to Programming (in C++) Recursion Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
Chapter 15 Recursion.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 13 - Recursion.
Recursion Chapter 7. Chapter Objectives  To understand how to think recursively  To learn how to trace a recursive method  To learn how to write recursive.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
15-1 Chapter-18: Recursive Methods –Introduction to Recursion –Solving Problems with Recursion –Examples of Recursive Methods.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-
Chapter 12 Recursion, Complexity, and Searching and Sorting
Analyzing Complexity of Lists OperationSorted Array Sorted Linked List Unsorted Array Unsorted Linked List Search( L, x ) O(logn) O( n ) O( n ) Insert(
Recursion Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Recursion. Recursive Methods HAVE: 1.A base case or termination condition that causes the method to end 2.A non-base case whose actions move the algorithm.
Sudeshna Sarkar, IIT Kharagpur 1 Functions : Recursion Lecture
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Recursion. Math Review Given the following sequence: a 1 = 1 a n = 2*a n-1 OR a n+1 = 2*a n What are the values of the following? a 2 = a 3 = a 4 =
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 18 Recursion Lecture 6 Dr. Musab.
ISOM MIS 215 Module 4 – Recursion. ISOM Where are we? 2 Intro to Java, Course Java lang. basics Arrays Introduction NewbieProgrammersDevelopersProfessionalsDesigners.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 15 * Recursive Algorithms.
Java Methods Big-O Analysis of Algorithms Object-Oriented Programming
CMPT 225 Recursion. Objectives Understand how the Fibonacci series is generated Recursive Algorithms  Write simple recursive algorithms  Analyze simple.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 18 Recursion.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 15 Recursion.
1 Chapter 8 Recursion. 2 Objectives  To know what is a recursive function and the benefits of using recursive functions (§8.1).  To determine the base.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
Recursion. What is Recursion? Method of solving problems Alternative to iteration All recursive solutions can be implemented iteratively Characteristic...
CS102 – Recursion David Davenport Bilkent University Ankara – Turkey
Recursion You may have seen mathematical functions defined using recursion Factorial(x) = 1 if x
Chapter 18 Recursion CS1: Java Programming Colorado State University
Chapter 14 Recursion.
Chapter 19: Recursion.
Recursion Topic 5.
Computer Science 4 Mr. Gerb
Towers of Hanoi Move n (4) disks from pole A to pole C
Chapter 19 Recursion.
Programming in Java: lecture 10
Java Software Structures: John Lewis & Joseph Chase
Chapter 12 Recursion (methods calling themselves)
Algorithm design and Analysis
Recursion Chapter 18.
Chapter 17 Recursion.
Chapter 18 Recursion.
Chapter 3 :Recursion © 2011 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

CS102 – Recursion David Davenport Bilkent University Ankara – Turkey Spring 2003

What is Recursion? Method of solving problems Alternative to iteration All recursive solutions can be implemented iteratively Characteristic... recursive methods call themselves recursive functions defined in terms of (simpler versions) themselves General recursive case & stopping cases

Factorial N Iterative N! = N * N-1 * N-2 … 2 * 1 Recursive 1! = 1 - stopping case N! = N * (N-1)! - general case implement & trace in Java

So, why use recursion? Advantages... Interesting conceptual framework Intuitive solutions to difficult problems But, disadvantages... requires more memory & time requires different way of thinking!

Towers of Hanoi The Problem… Rules only move one disk at a time can’t put a disk on a smaller one Monks believed world would end once solved for 64 disks! Takes 580 billion years! at one move per sec.

Hanoi… private void moveTower (int numDisks, int start, int end, int temp) { if (numDisks == 1) moveOneDisk (start, end); else { moveTower (numDisks-1, start, temp, end); moveOneDisk (start, end); moveTower (numDisks-1, temp, end, start); }

Print reverse Print first N values in reverse Simple iterative solution… Recursive? Hint - what is the simplest case? Write out sequence of cases & look for previous case within each case generalise & note stopping case! Given... print... 3, 6, 2, 7, 5

Print reverse - solution Solution form N’th N-1 To print N values in reverse order if N > 0 Print the N’th value & then Print the preceding N-1 values in reverse order Write Java & trace

Print forward Print set of values in normal order Solution form N’th N-1 To print N values in normal order if N > 0 Print the first N-1 values in normal order & then Print the N’th value Write Java & trace

Print – alternative solution Print set of values in order Alternative solution To print values btw S & E in order if S <= E Print the value at S & then Print the values btw S+1 & E in order Write Java & trace first Srest E

Find Max Find max of first N values To find max of N values if N = 1 return N’th value else return greater of N’th & max of preceding N-1 values N’thN-1 Think about solution in terms of these two sub- problems

Sequential search Search( first N values of X for target) if N = 0 return not found else if N’th value is target return found at N’th else return search( first N-1 values of X for target) N’thN-1 Think about simplest cases of problem & more general solution in terms of these two sub-problems O(N)

Binary Search Think about using telephone directory Values must be in order! Have knowledge of data distribution If unknown? (number guessing game) second halffirst half middle SE O(log 2 N)

Binary Search (continued…) Search( X btw S & E for target) if S > E return not found else if ( middle value is target) return found at middle else if ( target < middle value) return search( first half of X for target) else return search( second half of X for target) First half is S, middle-1 Second half is middle+1, E

Selection sort N’thN-1 selectionSort( first N values of X) if N > 1 locOfMax = findmax( first N values of X) exchange N’th value with value at locOfMax selectionSort( first N-1 values of X) O(N 2 ) locOfMax

QuickSort pivot O(Nlog 2 N) QuickSort( X btw S & E) if S < E pivot loc. = partition( X btw S & E) QuickSort( first part of X) QuickSort( second part of X) Sort second part Sort first part pivot First part is S to pivot loc.-1 Second part is pivot loc.+1 to E partition

MergeSort O(Nlog 2 N) MergeSort( X btw S & E) if S < E MergeSort( first half of X) MergeSort( second half of X) Merge( first & second halves of X) merge Merge is the basis of sequential processing Sort first half Sort second half

Counting Count number of values before zero count no. values before zero starting at S if value at S is zero return 0 else return 1 + count no. values starting at S+1 restfirst S Zero is sentinel value & so is guaranteed to exist. This is a common form of representation for strings!

Common mistakes! (1) sum = 0; public void count( int[] X, int S) { if ( X[S] != 0) { sum++; count( X, S+1); } Problems: Need another method to getCount() What happens if called again?

Common mistakes! (2) public int count( int[] X, int S) { int sum; if ( X[S] == 0) return sum; else { sum++; return count( X, S+1); } Problem: New instance of local variable for each instantiation!

Palindrome RADAR lastfirst middle isPalindrome( word) if first >= last return true else if first char of word != last char of word return false else return isPalindrome( middle of word)

Fibonacci Numbers Find fib(n) given the definition : fib(0) = 1 fib(1) = 1 fib(n) = fib(n-1) + fib(n-2)

Solution public int fib( int n ) { if ( n == 0 || n == 1 ) { return 1; } else { return fib( n - 1 ) + fib( n - 2 ); } naturally recursive, however better-off being solved iteratively

Caching solutions.. static int fib(int n) { int[] sols = new int[n + 1]; sols[0] = 1; sols[1] = 1; return fib(n, sols) } static int fib(int n, int[] sols) { if (sols[n] > 0) return sols[n]; int sol = fib(n-1, sols) + fib(n-2, sols); sols[n] = sol; return sol; }

Blob Count A Blob is the union of adjacent cells Cells are represented by a two dimensional array: boolean[][] isFull; The problem is to count the size of a blob starting from coordinates x, & y.

Blob Count, the plan have a recursive method that adds 1 to the count if the given cell is occupied, and recursively adds the numbers of 8 neighbors we need to remember which cells we already counted, and can use boolean[][] counted for this purpose

Blob count, algorithm public int count(boolean[][] cells, int x, int y) { boolean[][] counted = new boolean[cells.length][cells[0].length] return count_(cells, counted, x, y) }

Blob Algorithm private int count_(boolean[][] cells, boolean[][] counted, int x, int y) { if ( x = cells.length) return 0; if (y = cells[0].length) return 0; if ( counted[x][y]) return 0; if (!isFull[x][y]) return 0; counted[x][y] = true; return 1 + count_(cells, counted, x+1, y) + count_(cells, counted, x, y+1) + count_(cells, counted, x+1, y+1) + … }

The plan… Print set of N values forward & backward Repeat using S & E find max value search for target - sequential binary search sort - selection, quick, merge palindrome Count using S only Maze & blob counting Fractals? Recursive-descent-parsing? …on to data structures (stacks, queues, lists, trees, …)