Introduction to Data Structures and Algorithms Chapter 6 Recursion (1)

Slides:



Advertisements
Similar presentations
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.
Advertisements

More Recursion: Permutations and Towers of Hanoi COP 3502.
Introduction to Algorithms Quicksort
Starting Out with Java: From Control Structures through Objects
Back to Sorting – More efficient sorting algorithms.
Recursion Ellen Walker CPSC 201 Data Structures Hiram College.
Factorial Recursion stack Binary Search Towers of Hanoi
CS1101: Programming Methodology Recitation 9 – Recursion.
Recursion CSC 220: Data Structure Winter Introduction A programming technique in which a function calls itself. One of the most effective techniques.
Recursive Functions The Fibonacci function shown previously is recursive, that is, it calls itself Each call to a recursive method results in a separate.
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. 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)
©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.
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.
Chapter 19 Recursion.
Analysis of Recursive Algorithms
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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
1 Divide and Conquer Binary Search Mergesort Recurrence Relations CSE Lecture 4 – Algorithms II.
19-Aug-15 Simple Recursive Algorithms. 2 A short list of categories Algorithm types we will consider include: Simple recursive algorithms Backtracking.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
A Review of Recursion Dr. Jicheng Fu Department of Computer Science University of Central Oklahoma.
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Department of Computer Science Data Structures Using C++ 2E Chapter 6: Recursion Learn about recursive Definitions Algorithms Functions Explore the base.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Ceng-112 Data Structures I Chapter 6 Recursion.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 15: Recursion Starting Out with Java: From Control Structures.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 14: Recursion.
15-1 Chapter-18: Recursive Methods –Introduction to Recursion –Solving Problems with Recursion –Examples of Recursive Methods.
Data Structures and Abstractions with Java, 4e Frank Carrano
Recursion.
Recursion Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
1 CS 177 Week 16 Recitation Recursion. 2 Objective To understand and be able to program recursively by breaking down a problem into sub problems and joining.
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.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
COMP Recursion, Searching, and Selection Yi Hong June 12, 2015.
Recursion Recursion Chapter 12. Outline n What is recursion n Recursive algorithms with simple variables n Recursion and the run-time stack n Recursion.
Edited by Malak Abdullah Jordan University of Science and Technology Data Structures Using C++ 2E Chapter 6 Recursion.
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.
Chapter 18: Searching and Sorting Algorithms. Objectives In this chapter, you will: Learn the various search algorithms Implement sequential and binary.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 15 * Recursive Algorithms.
8.1 8 Algorithms Foundations of Computer Science  Cengage Learning.
1 Recursive algorithms Recursive solution: solve a smaller version of the problem and combine the smaller solutions. Example: to find the largest element.
Recursion ITI 1121 N. El Kadri. Reminders about recursion In your 1 st CS course (or its equivalent), you have seen how to use recursion to solve numerical.
Recursion COMP x1 Sedgewick Chapter 5. Recursive Functions problems can sometimes be expressed in terms of a simpler instance of the same problem.
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
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:
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
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 Data Structures CSCI 132, Spring 2016 Notes 16 Tail Recursion.
Chapter 9 Recursion. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe recursive function is –a.
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 19: Recursion.
Chapter 15 Recursion.
Data Structures and Programming Techniques
Chapter 15 Recursion.
Data Structures and Programming Techniques
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Recursion Chapter 10.
Data Structures Recursion CIS265/506: Chapter 06 - Recursion.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Chapter 12 Recursion (methods calling themselves)
2.3 Recursion do automated demo of towers of hanoi before class
Recursion.
Recursion.
Chapter 3 :Recursion © 2011 Pearson Addison-Wesley. All rights reserved.
Recursion Chapter 12.
Presentation transcript:

Introduction to Data Structures and Algorithms Chapter 6 Recursion (1)

Recursion Recursion Definition Process: –Expand: A function calls itself with “smaller parameter” –Converge: A function with parameter x uses the computation result of function with x-1. When terminate the sequence of recursive calls? –Base case: »A function call with the smallest parameter needs no further calls; it simply returns result.

Sum of Squares int SumSquares(int m, int n) { if (m < n) return m*m + SumSquares (m+1,n); else return m*m; }

Factorials Computation N ! = N × (N-1) × (n-2) × … × 1 Another way to compute factorial? –Instead of computing factorial, computing multiplication Basic Idea (tree structure): –N ! = N × (N -1) ! –(N -1) ! = (N -1) × (N -2) ! –… –1! = 1

int factorial(int n) { int result =1; for (int j=n; j>=1; j--) result *= j; return result; } int factorial(int n) { if (n==1) return 1; else return ( n * factorial (n-1) ); }

Reversing a List Partition the list into –Head --- one node –Tail --- the rest of the list Reverse the head and the tail (recursively) Combine the two reverse lists

Functions getHead getTail Node getHead( List mlist), returns the first node List getTail (List mlist), returns the sublist that results after removing the first node List Concat (List m1, List m2), joins two sublists

Recursive Reverse List List reverseL (List mlist) { List head; List tail; if (mlist.first == null) return null; else { head = getHead(mlist); tail = getTail(mlist); return concat (reserseL (tail), head); }

Binary Search Binary Search Algorithm (Chapter 2): –Order array elements –Compare the value of middle element with target –Based on comparison result, change range and middle element –Keep doing that until a match is found Note that each time we apply same logic to different range and middle element Can it be done recursively? How? –Develop a function called recFind(key, LowerBond, Upper Bound) –If key < middle element recFind (key, LowerBound, Middle-1) –If key > middle element recFind (key, Middle+1, UpperBound)

private int recFind(long searchKey, int lowerBound, int upperBound) { int curIn; curIn = (lowerBound + upperBound ) / 2; if(a[curIn]==searchKey) return curIn; // found it else if(lowerBound > upperBound) return nElems; // can't find it else // divide range { if(a[curIn] < searchKey) // it's in upper half return recFind(searchKey, curIn+1, upperBound); else // it's in lower half return recFind(searchKey, lowerBound, curIn-1); } // end else divide range } // end recFind()

Anagrams All possible permutations of the input string Example: anagrams of cat –cat; cta; atc; act; tca; tac Problem: how to compute all anagrams –Loop idea: many levels of loop –Recursive Idea: Anagrams(S) = the first character + anagrams (S-1) –How many choices for the first character ? –Anagrams (S-1) is different for each possible choice

Anagramming Recursive Algorithm –Anagram the rightmost n-1 letters –Shift n letters to left by one postion cat – atc – tca -- cat –Repeat these steps n times Trace anagramming recursive algorithm for the word “cat” –Figure 6.7

public static void doAnagram(int newSize) { int limit; if(newSize == 1) // base case return; // go no further for(int j=0; j<newSize; j++) // for each position, { doAnagram(newSize-1); // anagram remaining if(newSize==2) // if innermost, displayWord(); // display it rotate(newSize); // rotate word } }

// rotate left all chars from position to end public static void rotate(int newSize) { int j; int position = size - newSize; char temp = arrChar[position]; // save first letter for(j=position+1; j<size; j++) // shift others left arrChar[j-1] = arrChar[j]; arrChar[j-1] = temp; // put first on right }

Tower of Hanoi Demo A number of disks placed on three columns –S: source column –I: intermediate column –D: destination column Rule: –no larger disk is allowed to place on top of smaller disks

Idea: –Sub-tree with fewer disks –Sub-trees are formed many times Recursive algorithm –Move the sub-tree consisting of the top n-1 disks from S to I –Move the remaining disk (largest) from S to D –Move the sub-tree from I to D

class TowersApp { static int nDisks = 3; public static void main(String[] args) { doTowers(nDisks, 'A', 'B', 'C'); } // public static void doTowers(int topN, char src, char inter, char dest) { if(topN==1) System.out.println("Disk 1 from " + src + " to "+ dest); else { doTowers(topN-1, src, dest, inter); // src to inter System.out.println("Disk " + topN + " from " + src + " to "+ dest); doTowers(topN-1, inter, src, dest); // inter to dest } } // } // end class TowersApp Trace Algorithm: Page 279

Running time analysis: –Depends on number of recursive calls Examples: –Factorial O(?) –Binary search O(?) –Anagram O(?)

Divide-and-Conquer approach divide a big problem into two smaller problems and solve them separately. The process continues until you get to the base case, which can be solved easily Divide-and-conquer approach usually involves two recursive calls, one for each smaller problems Lots of time, you will see O(n2) algorithm can be improved to O(nlogn) with Divide-and-conquer approach

Exercise 1: String length computation –Compute the length of an input string recursively Exercise 2: Teddy Bear Game –Initially, you have initial number of bears –Each step, you can do one of the followings: Ask for increment number of bears Give away half of bears if you have even number of bears goaln –Goal: reach goal number of bears within n steps –How do you know if you can reach goal or not?