19-Aug-15 Simple Recursive Algorithms. 2 A short list of categories Algorithm types we will consider include: Simple recursive algorithms Backtracking.

Slides:



Advertisements
Similar presentations
Introduction to Algorithms Quicksort
Advertisements

Types of Algorithms.
Recursion, pt. 2: Thinking it Through. What is Recursion? Recursion is the idea of solving a problem in terms of solving a smaller instance of the same.
Main Index Contents 11 Main Index Contents Week 10 – Recursive Algorithms.
Factorial Recursion stack Binary Search Towers of Hanoi
Algorithm Strategies Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CS203 Programming with Data Structures Sorting California State University, Los Angeles.
Computer Science II Recursion Professor: Evan Korth New York University.
Recursion. Idea: Some problems can be broken down into smaller versions of the same problem Example: n! 1*2*3*…*(n-1)*n n*factorial of (n-1)
16-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
©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.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
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.
CS 206 Introduction to Computer Science II 10 / 14 / 2009 Instructor: Michael Eckmann.
Quicksort.
Recursion Road Map Introduction to Recursion Recursion Example #1: World’s Simplest Recursion Program Visualizing Recursion –Using Stacks Recursion Example.
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
Sorting. Introduction Assumptions –Sorting an array of integers –Entire sort can be done in main memory Straightforward algorithms are O(N 2 ) More complex.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Stacks (Revised and expanded from CIT 591). What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on.
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
Stacks. What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
28-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
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 A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Backtracking.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 15 Recursive Algorithms.
Recursion and Implementation of Functions
F453 Computing Searches. Binary Trees Not this kind of tree!
1 Time Analysis Analyzing an algorithm = estimating the resources it requires. Time How long will it take to execute? Impossible to find exact value Depends.
Fundamentals of Algorithms MCS - 2 Lecture # 7
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
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.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
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.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Outline Binary Trees Binary Search Tree Treaps. Binary Trees The empty set (null) is a binary tree A single node is a binary tree A node has a left child.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 15 * Recursive Algorithms.
Data Structure and Algorithms. Algorithms: efficiency and complexity Recursion Reading Algorithms.
Types of Algorithms. 2 Algorithm classification Algorithms that use a similar problem-solving approach can be grouped together We’ll talk about a classification.
CSE205 Review Session SAMUEL & JESSA. Recursion WHAT IS RECURSION?  Recursion is a tool a programmer can use to invoke a function call on itself. 
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
Quicksort This is probably the most popular sorting algorithm. It was invented by the English Scientist C.A.R. Hoare It is popular because it works well.
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
Maitrayee Mukerji. Factorial For any positive integer n, its factorial is n! is: n! = 1 * 2 * 3 * 4* ….* (n-1) * n 0! = 1 1 ! = 1 2! = 1 * 2 = 2 5! =
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Chapter 6 (Lafore’s Book) Recursion Hwajung Lee.  Definition: An algorithmic technique. To solve a problem on an instance of size n, the instance is:
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.
Sorting and Runtime Complexity CS255. Sorting Different ways to sort: –Bubble –Exchange –Insertion –Merge –Quick –more…
1 CSC 143 Recursion [Reading: Chapter 17]. 2 Recursion  A recursive definition is one which is defined in terms of itself.  Example:  Sum of the first.
Lecture 11 Recursion. A recursive function is a function that calls itself either directly, or indirectly through another function; it is an alternative.
1 Dr. Chow-Sing LinRecursion - CH 10 Problem Solving and Program Design in C Chapter 9 Recursion Chow-Sing Lin.
Introduction to Recursion
Java Methods AB Recursion Data Structures Maria Litvin Gary Litvin TM
Types of Algorithms.
Stacks.
Fundamentals of Programming
Types of Algorithms.
Recursion Data Structures.
Stacks.
Quicksort.
CSC 143 Recursion.
Types of Algorithms.
Quicksort.
Presentation transcript:

19-Aug-15 Simple Recursive Algorithms

2 A short list of categories Algorithm types we will consider include: Simple recursive algorithms Backtracking algorithms Divide and conquer algorithms Dynamic programming algorithms Greedy algorithms Branch and bound algorithms Brute force algorithms Randomized algorithms

3 Simple recursive algorithms A simple recursive algorithm: Solves the base cases directly Recurs with a simpler subproblem or subproblems May do some extra work to convert the solution to the simpler subproblem into a solution to the given problem I call these “simple” because several of the other algorithm types are inherently recursive

4 Some example algorithms We will look briefly at the following simple recursive algorithms: Factorial All permutations Tree traversal Flood fill Quicksort Towers of Hanoi Ackermann’s function We will also consider the equivalence of loops and recursion

5 Factorial The factorial function is the “Hello World” of recursion public static long factorial(int n) { if (n <= 1) return 1; else return n * factorial(n - 1); } The problem with this example is that it can be done almost as easily with a loop (so why bother learning recursion?) public static long factorial(int n) { int result = 1; while (n > 1) { result *= n; n--; } } In the following slides, we look at some example problems for which recursion really is simpler

6 Permutations A permutation of a set of objects is a particular ordering of those objects When we speak of “all permutations” of a set, we mean all possible ways of ordering those objects Examples: Given the empty set { }, the only possible permutation is { } Given the set {A}, the only possible permutation is {A} Given the set {A, B}, the possible permutations are {AB, BA} Given the set {A, B, C}, the possible permutations are {ABC, ACB, BAC, BCA, CAB, CBA} Etc.

7 Finding all permutations of n objects To find all permutations of n objects: Find all permutations of n-1 of those objects Insert the remaining object into all possible positions of each permutation of n-1 objects Example: To find all permutations of 3 objects {A, B, C} Find all permutations of 2 of the objects, say B and C : B C and C B Insert the remaining object, A, into all possible positions (marked by ^) in each of the permutations of B and C : ^ B ^ C ^ and ^ C ^ B ^ ABC BAC BCA ACB CAB CBA

8 A program to find permutations We will develop complete Java code to find all permutations of a nonempty String of characters ArrayList permutationsOf(String s) {  if (s.length() == 1) {  // return a new ArrayList containing just s  }  else {  // separate the first character from the rest  // get all permutationsOf ( the rest of the characters )  // for each permutation, // add the first character in all possible positions, and // put each result into a new ArrayList  }  // return the new ArrayList }}

9 permutationsOf(String), part I  ArrayList permutationsOf(String s) {  ArrayList result = new ArrayList ();  if (s.length() == 1) { // base case  // return a new ArrayList containing just s  result.add(s);  return result;  }  // continued...

10 permutationsOf(String), part II  else {  // separate the first character from the rest  char first = s.charAt(0);  String rest = s.substring(1);  // get all permutationsOf the rest of the characters  ArrayList simpler = permutationsOf(rest); // recursive step  // for each permutation,  for (String permutation : simpler) { // extra work // add the first character in all possible positions, and  ArrayList additions = insertAtAllPositions(first, permutation); // put each result into a new ArrayList  result.addAll(additions);  }  return result;  } }}

11 Insert in all positions Given one String representing one permutation of n-1 characters, we want to return all permutations resulting from inserting a given character in all n possible positions  private ArrayList insertAtAllPositions(char ch, String s) {  ArrayList result = new ArrayList ();  for (int i = 0; i <= s.length(); i++) {  String inserted = s.substring(0, i) + ch + s.substring(i);  result.add(inserted); }  return result; }

12 A tree is composed of nodes Each node contains a value Each node may have children One special node is called the root of the tree Nodes with children are called internal nodes Nodes without children are called leaves Trees A CBDE GFHJKI LMN root internal nodes leaves

13 Tree traversals It’s easy to traverse (“walk”) a tree recursively Here’s a recursive method which, if called with the root of a tree, will print out all the values in the tree: void printTree(Node n) { print the value in node n; for each child c of n, printTree(c) Or, in actual Java:  void printTree(Node n) {  System.out.println(n.getValue()); Iterator iter = node.getChildren().iterator(); while (iter.hasNext()) { printTree(iter.next()); } } Many data structures are best handled recursively

14 Flood fill To “flood fill” an area with color oldColor, starting from a particular pixel of color newColor: void floodFill(Pixel p, Color oldColor, Color newColor) { if p is not oldColor, just return else { set color of p to newColor for each pixel q adjacent to p (horizontally or vertically), floodFill(q, oldColor, newColor) } }

15 Quicksort Quicksort is (in some sense) the fastest sorting algorithm known From an array of numbers, pick one to use as a pivot (we’ll use 45 as the pivot) Partition the numbers into those smaller than or equal to the pivot, and those larger than the pivot Now quicksort the left side: And the right side:

16 Towers of Hanoi “Towers of Hanoi” is commonly used as an example of a problem with a simple recursive solution There are three pegs The first (source) peg holds some number of rings You want to move all rings to the last (destination) peg You can only move one ring at a time You can never put a larger ring on top of a smaller ring You have one auxiliary peg you can use src aux dest

17 Solution to Towers of Hanoi Move the top n-1 rings from src to aux (recursively) Move the largest ring from src to dest Move the n-1 rings from aux to dest (recursively) Notice that there are two recursive calls in this algorithm Hence, the number of calls doubles at each level of the recursion For a large number of rings, this is a very expensive algorithm! src aux dest

18 Ackermann’s function Ackermann’s function is a deceptively simple little set of equations: A(0, y) = y + 1 A(x, 0) = A(x - 1, 1) A(x, y) = A(x - 1, A(x, y - 1)) This can easily be written as a recursive method A(4, 0) = 13 A(4, 1) = A(4, 2) = After this, the numbers start to get huge quickly This function takes a long time to compute (why?)

19 Recursion isn’t necessary Computers don’t have “recursive hardware”! When a higher-level language is compiled, recursive calls are implemented with a stack When you enter a method, all its local variables (including its formal parameters) are created and put onto a stack The method operates on its own copies of the local variables When the method exits, its local variables are removed from the stack The compiler changes recursive code into nonrecursive code It follows, then, that anything you could do recursively, you could also do nonrecursively by using loops and a stack

20 Tree traversals, again Here’s a recursive method which, if called with the root of a tree, will print out all the values in the tree: void printTree(Node n) { print the value in node n; for each child c of n { printTree(c) } } Here it is without recursion: void printTree(Node n) { create a new stack s; push n onto s; while (s is not empty) { remove a node m from s and print it push the children of m (if any) onto stack s } }

21 Loops aren’t necessary You can replace any recursion with loops (and a stack for local variables) In addition, you can replace any loop with a recursion For example, consider zeroing out an array: static void zeroOut(int[] a) { for (int i = 0; i < a.length; i++) a[i] = 0; } Or: static void zeroOut(int[] a, int n) { // call with n = 0 if (n < a.length) { a[n] = 0; zeroOut(a, n + 1); } } Of course, this is an example, not a proof It can be proved (we won’t do it here) that loops can always be replaced by recursions

22 Closing comments The intent of this set of slides is to get you more familiar with some of the uses of recursion Recursion and loops are, in some sense, equivalent-- anything you can do with one, you can do with the other Once you understand recursion, though, it is often simpler to use recursion than to use loops

23 The End