Recursion CITS1001.

Slides:



Advertisements
Similar presentations
Introduction to Recursion and Recursive Algorithms
Advertisements

CS 1031 Recursion (With applications to Searching and Sorting) Definition of a Recursion Simple Examples of Recursion Conditions for Recursion to Work.
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. Binary search example postponed to end of lecture.
1 Sorting Algorithms (Part II) Overview  Divide and Conquer Sorting Methods.  Merge Sort and its Implementation.  Brief Analysis of Merge Sort.  Quick.
Scott Grissom, copyright 2004 Chapter 5 Slide 1 Analysis of Algorithms (Ch 5) Chapter 5 focuses on: algorithm analysis searching algorithms sorting algorithms.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
1 Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  Chapter 11 of the book.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 1 What comes next? Recursion (Chapter 15) Recursive Data Structures.
Quicksort. Quicksort I To sort a[left...right] : 1. if left < right: 1.1. Partition a[left...right] such that: all a[left...p-1] are less than a[p], and.
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.
Quicksort.
Recursion.
Chapter 11 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
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.
1 Algorithmic analysis Introduction. This handout tells you what you are responsible for concerning the analysis of algorithms You are responsible for:
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
Recursion.
1 Decrease-and-Conquer Approach Lecture 06 ITS033 – Programming & Algorithms Asst. Prof. Dr. Bunyarit Uyyanonvara IT Program, Image and Vision Computing.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
1 Recursion Algorithm Analysis Standard Algorithms Chapter 7.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Week 5 - Monday.  What did we talk about last time?  Linked list implementations  Stacks  Queues.
Chapter 12 Recursion, Complexity, and Searching and Sorting
1 Programming with Recursion. 2 Recursive Function Call A recursive call is a function call in which the called function is the same as the one making.
Recursion Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
Searching. RHS – SOC 2 Searching A magic trick: –Let a person secretly choose a random number between 1 and 1000 –Announce that you can guess the number.
1 TCSS 143, Autumn 2004 Lecture Notes Recursion Koffman/Wolfgang Ch. 7, pp ,
CSIS 123A Lecture 9 Recursion Glenn Stevenson CSIS 113A MSJC.
CSE 501N Fall ‘09 12: Recursion and Recursive Algorithms 8 October 2009 Nick Leidenfrost.
11-1 Recursive Thinking A recursive definition is one which uses the word or concept being defined in the definition itself When defining an English word,
Lecture 7 b Recursion is a fundamental programming technique that can provide an elegant solution to certain kinds of problems b Today: thinking in a recursive.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
EFFICIENCY & SORTING II CITS Scope of this lecture Quicksort and mergesort Performance comparison.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 8: Recursion Presentation slides for Java Software Solutions for AP* Computer Science 3rd.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
Winter 2006CISC121 - Prof. McLeod1 Stuff No stuff today!
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Recursion.
Recursion A recursive definition is one which uses the word or concept being defined in the definition itself Example: “A computer is a machine.
Chapter 111 Recursion Chapter Objectives become familiar with the idea of recursion learn to use recursion as a programming tool become familiar.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
Function Recursion to understand recursion you must understand recursion.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Recursion CITS1001.
Abdulmotaleb El Saddik University of Ottawa
Decrease-and-Conquer Approach
COP 3503 FALL 2012 Shayan Javed Lecture 15
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Recursion CITS1001.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Recursive Definitions
Chapter 12 Recursion (methods calling themselves)
Recursion Chapter 11.
Chapter 11 Recursion.
11 Recursion Software Solutions Lewis & Loftus java 5TH EDITION
Recursion Chapter 11.
Java Software Solutions Foundations of Program Design Sixth Edition
Searching.
Presentation transcript:

recursion CITS1001

Scope of this lecture Concept of recursion Simple examples of recursion

Recursion We have already seen that a method can call other methods Either in the same class or in other classes However a method can also call itself This self-referential behaviour is known as recursion We saw examples with Quicksort and Mergesort Recursion is an extremely powerful technique for expressing certain complex programming tasks It provides a very natural way to decompose problems There are computational costs associated with recursion The careful programmer will always be aware of these

The simplest example The factorial of a positive integer k is the product of the integers between 1 and k k! = 1 × 2 × 3 × … × (k–1) × k In Java: private long factorial(long k) { long z = 1; for (long i = k; i > 1; i––) z *= i; return z; }

Think different! k! = 1 × 2 × 3 × … × (k–1) × k This is a recursive definition of factorial Factorial defined in terms of itself It uses factorial to define factorial

Something else is required 4! = 4 × 3! = 4 × 3 × 2! = 4 × 3 × 2 × 1! = 4 × 3 × 2 × 1 × 0! = 4 × 3 × 2 × 1 × 0 × (–1)! … We need something to tell it when to stop! The base case of the recursion is when we know the result directly 1! = 1

Recursive factorial in Java private long factorial(long k) { if (k == 1) return 1; else return k * factorial(k – 1); } In the base case factorial stops and returns a result directly In the recursive case factorial calls itself with a smaller argument

How does Java execute this? private long factorial(long k) { if (k == 1) return 1; else return k * factorial(k – 1); } factorial(4) = 4 * 6 factorial(3) factorial(3) = 3 * factorial(2) 2 factorial(2) = 2 * factorial(1) 1 factorial(1) = 1

Every k is a local variable Each invocation of factorial has its own independent parameter k factorial(4) creates a local variable k = 4 Then factorial(3) creates its own local variable k = 3 Then factorial(2) creates its own local variable k = 2 Then factorial(1) creates its own local variable k = 1 The compiler manages all of these variables for you, behind the scenes Exactly as if you called any other method multiple times Each invocation would have its own local variable(s)

Order is crucial This will not work! private long factorial(long k) { return k * factorial(k – 1); if (k == 1) return 1; }

Ingredients for a recursive definition Every recursive definition must have two parts One or more base cases Each base case represents some “trivial case”, where we return a result directly These are essential so that the recursion doesn’t go on forever Often either a number being 0 or 1, or an array segment having length 0 or 1 One or more recursive cases The result is defined in terms of one or more calls to the same method, but with different parameters The new parameters must be “closer to” the base case(s) in some sense Often a number getting smaller, or an array segment getting shorter, or maybe two numbers getting closer together

Multiple base cases Each Fibonacci number is the sum of the previous two Fibonacci numbers F1 = 1 F2 = 2 Fk = Fk–1 + Fk–2 1, 2, 3, 5, 8, 13, 21, …

Fibonacci in Java This version is appalling slow, though private long fib(long k) { if (k == 1) return 1; else if (k == 2) return 2; else return fib(k – 1) + fib(k – 2); } This version is appalling slow, though The number of calls to calculate fib(k) is Fk

Faster Fibonacci The number of calls to calculate fib1(k) is k–1 private long fib1(long k) { return fib2(k, 1, 1); } private long fib2(long k, long x, long y) if (k == 1) return x; else return fib2(k – 1, x + y, x); The number of calls to calculate fib1(k) is k–1 Make sure you understand that fib1(k) == fib(k)

Really fast Fibonacci Constant time! private long fib3(long k) { double sq5 = Math.sqrt(5); double phi = (1 + sq5) / 2; return Math.round(Math.pow(phi, k + 1) / sq5); } Constant time! Make sure you understand that fib3(k) == fib(k)

Mergesort In each recursive call, u – l gets smaller When u == l, we hit the base case: do nothing! public static void mergeSort(int[] a){ msort(a, 0, a.length - 1); } // sort a[l..u] inclusive private static void msort(int[] a, int l, int u){ if (l < u) {int m = (l + u) / 2; msort(a, l, m); msort(a, m + 1, u); merge(a, l, m, u);}

Quicksort Again, in each recursive call, u – l gets smaller p will always be between l and u public static void quickSort(int[] a) { qsort(a, 0, a.length – 1); } // sort a[l..u] inclusive private static void qsort(int[] a, int l, int u) { if (l < u) { int p = partition(a, l, u); qsort(a, l, p – 1); qsort(a, p + 1, u);

Binary search We saw previously that linear search is very slow for large data If the data is sorted, we can use the much faster binary search Assume we are given an array of numbers in ascending order, and we want to check if the number z is in the array Inspect the middle number If the middle number is smaller than z, then if z is in the array, it must be in the top half All numbers in the bottom half are smaller than z and can be ignored If the middle number is larger than z, then if z is in the array, it must be in the bottom half

Code for binary search public static boolean binarySearch(int[] a, int z) { return bs(a, 0, a.length - 1, z); } // search a[l..u] inclusive for z private static boolean bs(int[] a, int l, int u, int z) if (l == u) return a[l] == z; else int m = (l + u) / 2; if (a[m] < z) return bs(a, m + 1, u, z); else return bs(a, l, m, z);

Binary search in action Searching for 29 3 5 6 11 12 14 17 20 26 28 31 32 35 39 41 Not found!

Performance of binary search Binary search is fast for the same reason that Quicksort and Mergesort are fast In each recursive call, the size of the array that must be searched is reduced by a factor of two So there will be log2n+1 calls, where n is the size of the original array And also the base case gets hit for the same reason as before In each recursive call, u–l defines the length of the array segment u–l gets smaller in each call When u–l hits 0, we use the base case