Recursion CS 308 – Data Structures. What is recursion? smaller version Sometimes, the best way to solve a problem is by solving a smaller version of the.

Slides:



Advertisements
Similar presentations
Sorted Lists CS Data Structures Sections 4.1, 4.2 & 4.3.
Advertisements

Recursion vs. Iteration The original Lisp language was truly a functional language: –Everything was expressed as functions –No local variables –No iteration.
Factorial Recursion stack Binary Search Towers of Hanoi
Chapter 4 ADT Sorted List.
Recursion Rosen 5 th ed., § Recursion Sometimes, defining an object explicitly might be difficult.Sometimes, defining an object explicitly might.
Sorted Lists CS Data Structures. Sorted List Specification (partial) InsertItem (ItemType item) Function: Adds item to list Preconditions: (1) List.
Implementing an Unsorted List as a Linked Structure CS 308 – Data Structures.
Recursion. Binary search example postponed to end of lecture.
Programming with Recursion
Recursion.
1 Chapter 7 Recursion. 2 What Is Recursion? l Recursive call A method call in which the method being called is the same as the one making the call l Direct.
5 Linked Structures. 2 Definition of Stack Logical (or ADT) level: A stack is an ordered group of homogeneous items (elements), in which the removal and.
Doubly Linked Lists CS 308 – Data Structures. Node data info: the user's data next, back: the address of the next and previous node in the list.back.next.info.
1 Fall Chapter 4 ADT Sorted List. 2 Goals Describe the Abstract Data Type Sorted List from three perspectives Implement the following Sorted List.
Implementing a Sorted List as a Linked Structure CS 308 – Data Structures.
Chapter 3: Recursive Algorithms
Recursion CS Goals Discuss recursion as another form of repetition Do the following tasks, given a recursive routine Determine whether the routine.
CS Discrete Mathematical Structures Mehdi Ghayoumi MSB rm 132 Ofc hr: Thur, 9:30-11:30a.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Chapter 2 Recursion: The Mirrors CS Data Structures Mehmet H Gunes Modified from authors’ slides.
1 Storage Classes, Scope, and Recursion Lecture 6.
Chapter 4 ADT Sorted List. 2 Goals Describe the Abstract Data Type Sorted List from three perspectives Implement the following Sorted List operations.
12-CRS-0106 REVISED 8 FEB 2013 KUG1C3 Dasar Algoritma dan Pemrograman.
CS 1704 Introduction to Data Structures and Software Engineering.
Recursion l Powerful Tool l Useful in simplifying a problem (hides details of a problem) l The ability of a function to call itself l A recursive call.
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 CS 3358 – Data Structures. Big Picture Our objective is to write a recursive program and convince ourselves it is correct with the minimum amount.
1 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus and Robert Moyer, Montgomery County Community.
Suppose you have a problem involving N data points. Recursive solution of such problem is a follows: If the problem can be solved directly for N points.
CIS 068 Welcome to CIS 068 ! Stacks and Recursion.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County.
Computer Science and Software Engineering University of Wisconsin - Platteville 9. Recursion Yan Shi CS/SE 2630 Lecture Notes Partially adopted from C++
Recursion CS 302 – Data Structures Chapter 7. What is recursion? smaller A technique that solves problem by solving smaller versions of the same problem!
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Recursion.
1 Nell Dale Chapter 8 Binary Search Trees Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data.
Chapter 6 Recursion. Solving simple problems Iteration can be replaced by a recursive function Recursion is the process of a function calling itself.
1 Lecture 3 Part 2 Storage Classes, Scope, and Recursion.
1 C++ Plus Data Structures Nell Dale Chapter 5 Linked Structures Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
Chapter 4 ADT Sorted List. Sorted Type Class Interface Diagram SortedType class IsFull GetLength ResetList DeleteItem PutItem MakeEmpty GetItem Private.
Tail Recursion l The case in which a function contains only a single recursive call and it is the last statement to be executed in the function. l Tail.
Chapter 7 Programming with Recursion. What Is Recursion? Recursive call A method call in which the method being called is the same as the one.
Chapter 6 Lists Plus Lecture 12. What is a Circular Linked List? A circular linked list is a list in which every node has a successor; the “last” element.
CS 302 – Data Structures Sections 3.1, 3.2, 3.4 & 3.5
1 Recursive algorithms Recursive solution: solve a smaller version of the problem and combine the smaller solutions. Example: to find the largest element.
Recursion. What is recursion? smaller version Sometimes, the best way to solve a problem is by solving a smaller version of the exact same problem first.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Lecture #3 Analysis of Recursive Algorithms
12-CRS-0106 REVISED 8 FEB 2013 KUG1C3 Dasar Algoritma dan Pemrograman.
Data Structures I (CPCS-204) Week # 5: Recursion Dr. Omar Batarfi Dr. Yahya Dahab Dr. Imtiaz Khan.
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.
递归算法的效率分析. When a function is called... A transfer of control occurs from the calling block to the code of the function --It is necessary that there be.
Recursion Powerful Tool
Programming with Recursion
Recursion DRILL: Please take out your notes on Recursion
Computer Science 4 Mr. Gerb
Programming with Recursion
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Recursion Data Structures.
When a function is called...
Yan Shi CS/SE 2630 Lecture Notes
CSI 1340 Introduction to Computer Science II
Data Structures and Algorithms Memory allocation and Dynamic Array
Recursion.
Advanced Analysis of Algorithms
Presentation transcript:

Recursion CS 308 – Data Structures

What is recursion? smaller version Sometimes, the best way to solve a problem is by solving a smaller version of the exact same problem first smaller problem Recursion is a technique that solves a problem by solving a smaller problem of the same type

When you turn this into a program, you end up with functions that call themselves (recursive functions) int f(int x) { int y; if(x==0) return 1; else { y = 2 * f(x-1); return y+1; }

Problems defined recursively There are many problems whose solution can be defined recursively Example: n factorial 1if n = 0 n!= (recursive solution) (n-1)!*nif n > 0 1if n = 0 n!= (closed form solution) 1*2*3*…*(n-1)*nif n > 0

Coding the factorial function Recursive implementation int Factorial(int n) { if (n==0) // base case return 1; else return n * Factorial(n-1); }

Coding the factorial function (cont.) Iterative implementation int Factorial(int n) { int fact = 1; for(int count = 2; count <= n; count++) fact = fact * count; return fact; }

Another example: n choose k (combinations) Given n things, how many different sets of size k can be chosen? n n-1 n-1 = +, 1 < k < n(recursive solution) k k k-1 n n! =, 1 < k < n(closed-form solution) k k!(n-k)! with base cases: n = n (k = 1), = 1 (k = n) 1 n

int Combinations(int n, int k) { if(k == 1) // base case 1 return n; else if (n == k) // base case 2 return 1; else return(Combinations(n-1, k) + Combinations(n-1, k-1)); } n choose k (combinations)

Recursion vs. iteration Iteration can be used in place of recursion –An iterative algorithm uses a looping construct –A recursive algorithm uses a branching structure Recursive solutions are often less efficient, in terms of both time and space, than iterative solutions Recursion can simplify the solution of a problem, often resulting in shorter, more easily understood source code

How do I write a recursive function? Determine the size factor Determine the base case(s) (the one for which you know the answer) Determine the general case(s) (the one where the problem is expressed as a smaller version of itself) Verify the algorithm (use the "Three-Question-Method")

Three-Question Verification Method 1.The Base-Case Question: Is there a nonrecursive way out of the function, and does the routine work correctly for this "base" case? 2.The Smaller-Caller Question: Does each recursive call to the function involve a smaller case of the original problem, leading inescapably to the base case? 3.The General-Case Question: Assuming that the recursive call(s) work correctly, does the whole function work correctly?

Recursive binary search Non-recursive implementation template void SortedType ::RetrieveItem(ItemType& item, bool& found) { int midPoint; int first = 0; int last = length - 1; found = false; while( (first <= last) && !found) { midPoint = (first + last) / 2; if (item < info[midPoint]) last = midPoint - 1; else if(item > info[midPoint]) first = midPoint + 1; else { found = true; item = info[midPoint]; }

What is the size factor? The number of elements in (info[first]... info[last]) What is the base case(s)? (1) If first > last, return false (2) If item==info[midPoint], return true What is the general case? if item < info[midPoint] search the first half if item > info[midPoint], search the second half Recursive binary search (cont’d)

template bool BinarySearch(ItemType info[], ItemType& item, int first, int last) { int midPoint; if(first > last) // base case 1 return false; else { midPoint = (first + last)/2; if(item < info[midPoint]) return BinarySearch(info, item, first, midPoint-1); else if (item == info[midPoint]) { // base case 2 item = info[midPoint]; return true; } else return BinarySearch(info, item, midPoint+1, last); } Recursive binary search (cont’d)

template void SortedType ::RetrieveItem (ItemType& item, bool& found) { found = BinarySearch(info, item, 0, length-1); } Recursive binary search (cont’d)

How is recursion implemented? What happens when a function gets called? int a(int w) { return w+w; } int b(int x) { int z,y; ……………… // other statements z = a(x) + y; return z; }

What happens when a function is called? (cont.) An activation record is stored into a stack (run- time stack) 1)The computer has to stop executing function b and starts executing function a 2)Since it needs to come back to function b later, it needs to store everything about function b that is going to need (x, y, z, and the place to start executing upon return) 3)Then, x from a is bounded to w from b 4)Control is transferred to function a

After function a is executed, the activation record is popped out of the run-time stack All the old values of the parameters and variables in function b are restored and the return value of function a replaces a(x) in the assignment statement What happens when a function is called? (cont.)

What happens when a recursive function is called? Except the fact that the calling and called functions have the same name, there is really no difference between recursive and nonrecursive calls int f(int x) { int y; if(x==0) return 1; else { y = 2 * f(x-1); return y+1; }

=f(3) =f(2) =f(1) 2*f(2) 2*f(1) =f(0)

Recursive InsertItem (sorted list) location

What is the size factor? The number of elements in the current list What is the base case(s)? 1)If the list is empty, insert item into the empty list 2)If item info, insert item as the first node in the current list What is the general case? Insert(location->next, item) Recursive InsertItem (sorted list)

template void Insert(NodeType * &location, ItemType item) { if(location == NULL) || (item info)) { // base cases NodeType * tempPtr = location; location = new NodeType ; location->info = item; location->next = tempPtr; } else Insert(location->next, newItem); // general case } template void SortedType ::InsertItem(ItemType newItem) { Insert(listData, newItem); } Recursive InsertItem (sorted list)

- No "predLoc" pointer is needed for insertion location

Recursive DeleteItem (sorted list) location

What is the size factor? The number of elements in the list What is the base case(s)? If item == location->info, delete node pointed by location What is the general case? Delete(location->next, item) Recursive DeleteItem (sorted list) (cont.)

template void Delete(NodeType * &location, ItemType item) { if(item == location->info)) { NodeType * tempPtr = location; location = location->next; delete tempPtr; } else Delete(location->next, item); } template void SortedType ::DeleteItem(ItemType item) { Delete(listData, item); } Recursive DeleteItem (sorted list) (cont.)

Recursion can be very inefficient is some cases 15

Deciding whether to use a recursive solution When the depth of recursive calls is relatively "shallow" The recursive version does about the same amount of work as the nonrecursive version The recursive version is shorter and simpler than the nonrecursive solution

Exercises 7-12, 15