SlideShare a Scribd company logo
Recursion
CS 308 – Data Structures
What is recursion?
• Sometimes, the best way to solve a problem
is by solving a smaller version of the exact
same problem first
• 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
1 if n = 0
n!= (recursive solution)
(n-1)!*n if n > 0
1 if n = 0
n!= (closed form solution)
1*2*3*…*(n-1)*n if 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
= 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<class ItemType>
void SortedType<ItemType>::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<class ItemType>
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<class ItemType>
void SortedType<ItemType>::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)
2*f(1)
=f(0)
Recursive InsertItem (sorted list)
location
location
location
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 < location->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 <class ItemType>
void Insert(NodeType<ItemType>* &location, ItemType item)
{
if(location == NULL) || (item < location->info)) { // base cases
NodeType<ItemType>* tempPtr = location;
location = new NodeType<ItemType>;
location->info = item;
location->next = tempPtr;
}
else
Insert(location->next, newItem); // general case
}
template <class ItemType>
void SortedType<ItemType>::InsertItem(ItemType newItem)
{
Insert(listData, newItem);
}
Recursive InsertItem (sorted list)
- No "predLoc" pointer is needed for insertion
location
Recursive DeleteItem (sorted list)
location
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 <class ItemType>
void Delete(NodeType<ItemType>* &location, ItemType item)
{
if(item == location->info)) {
NodeType<ItemType>* tempPtr = location;
location = location->next;
delete tempPtr;
}
else
Delete(location->next, item);
}
template <class ItemType>
void SortedType<ItemType>::DeleteItem(ItemType item)
{
Delete(listData, item);
}
Recursive DeleteItem (sorted list)
(cont.)
Recursion can be very inefficient
is some cases
+
=
=
=
=
=
=
+ +
+ + + +
+
+ + + + +
+
+
+
+
+ + +
+ + + + + + +
+ +
+
+
+
+
+
+
+
+
+
3
3
Comb (3, 1)
2
Comb (2, 1)
1
Comb (2, 2)
Comb (3, 2)
Comb (4,2)
2
Comb (2, 1)
1
Comb (2, 2)
Comb (3, 2)
1
1
Comb (3, 3)
Comb (4, 3)
Comb (5, 3)
2
Comb (2, 1)
1
Comb (2, 2)
Comb (3, 2)
1
1
Comb (3, 3)
Comb (4, 3)
1
1
1
Comb (4, 4)
Comb (5, 4)
Comb (6,4)
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

More Related Content

Similar to Recursion.ppt

Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
Francesco Bruni
 
Tower of Hanoi.ppt
Tower of Hanoi.pptTower of Hanoi.ppt
Tower of Hanoi.ppt
SACHINVERMA255386
 
BinarySearchTrees.ppt
BinarySearchTrees.pptBinarySearchTrees.ppt
BinarySearchTrees.ppt
SARATHGARIKINA
 
BinarySearchTrees.ppt
BinarySearchTrees.pptBinarySearchTrees.ppt
BinarySearchTrees.ppt
ItsStranger1
 
BinarySearchTrees (1).ppt
BinarySearchTrees (1).pptBinarySearchTrees (1).ppt
BinarySearchTrees (1).ppt
plagcheck
 
Binary searchtrees
Binary searchtreesBinary searchtrees
Binary searchtrees
HasnainBaloch12
 
BinarySearchTrees.ppt
BinarySearchTrees.pptBinarySearchTrees.ppt
BinarySearchTrees.ppt
plagcheck
 
data structure very BinarySearchTrees.ppt
data structure very BinarySearchTrees.pptdata structure very BinarySearchTrees.ppt
data structure very BinarySearchTrees.ppt
DharmannaRathod1
 
C++ Windows Forms L06 - Utlitity and Strings
C++ Windows Forms L06 - Utlitity and StringsC++ Windows Forms L06 - Utlitity and Strings
C++ Windows Forms L06 - Utlitity and Strings
Mohammad Shaker
 
recursion.ppt
recursion.pptrecursion.ppt
recursion.ppt
NISHASOMSCS113
 
Algorithm
AlgorithmAlgorithm
Algorithm
sultanarun
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
BG Java EE Course
 
Fundamental computing algorithms
Fundamental computing algorithmsFundamental computing algorithms
Fundamental computing algorithms
Ganesh Solanke
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
Julie Iskander
 
Lecture07 the linked-list_as_a_data_structure_v3
Lecture07 the linked-list_as_a_data_structure_v3Lecture07 the linked-list_as_a_data_structure_v3
Lecture07 the linked-list_as_a_data_structure_v3
Hariz Mustafa
 
Advanced data structure
Advanced data structureAdvanced data structure
Advanced data structure
Shakil Ahmed
 
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
Venkateswara Babu Ravipati
 
Recursion and Sorting Algorithms
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting Algorithms
Afaq Mansoor Khan
 
Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”
Platonov Sergey
 
Exam 1 Review CS 1803
Exam 1 Review CS 1803Exam 1 Review CS 1803
Exam 1 Review CS 1803
Will Barr
 

Similar to Recursion.ppt (20)

Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
 
Tower of Hanoi.ppt
Tower of Hanoi.pptTower of Hanoi.ppt
Tower of Hanoi.ppt
 
BinarySearchTrees.ppt
BinarySearchTrees.pptBinarySearchTrees.ppt
BinarySearchTrees.ppt
 
BinarySearchTrees.ppt
BinarySearchTrees.pptBinarySearchTrees.ppt
BinarySearchTrees.ppt
 
BinarySearchTrees (1).ppt
BinarySearchTrees (1).pptBinarySearchTrees (1).ppt
BinarySearchTrees (1).ppt
 
Binary searchtrees
Binary searchtreesBinary searchtrees
Binary searchtrees
 
BinarySearchTrees.ppt
BinarySearchTrees.pptBinarySearchTrees.ppt
BinarySearchTrees.ppt
 
data structure very BinarySearchTrees.ppt
data structure very BinarySearchTrees.pptdata structure very BinarySearchTrees.ppt
data structure very BinarySearchTrees.ppt
 
C++ Windows Forms L06 - Utlitity and Strings
C++ Windows Forms L06 - Utlitity and StringsC++ Windows Forms L06 - Utlitity and Strings
C++ Windows Forms L06 - Utlitity and Strings
 
recursion.ppt
recursion.pptrecursion.ppt
recursion.ppt
 
Algorithm
AlgorithmAlgorithm
Algorithm
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
 
Fundamental computing algorithms
Fundamental computing algorithmsFundamental computing algorithms
Fundamental computing algorithms
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Lecture07 the linked-list_as_a_data_structure_v3
Lecture07 the linked-list_as_a_data_structure_v3Lecture07 the linked-list_as_a_data_structure_v3
Lecture07 the linked-list_as_a_data_structure_v3
 
Advanced data structure
Advanced data structureAdvanced data structure
Advanced data structure
 
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
 
Recursion and Sorting Algorithms
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting Algorithms
 
Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”Bartosz Milewski, “Re-discovering Monads in C++”
Bartosz Milewski, “Re-discovering Monads in C++”
 
Exam 1 Review CS 1803
Exam 1 Review CS 1803Exam 1 Review CS 1803
Exam 1 Review CS 1803
 

Recently uploaded

一比一原版(UCSB文凭证书)圣芭芭拉分校毕业证如何办理
一比一原版(UCSB文凭证书)圣芭芭拉分校毕业证如何办理一比一原版(UCSB文凭证书)圣芭芭拉分校毕业证如何办理
一比一原版(UCSB文凭证书)圣芭芭拉分校毕业证如何办理
nuttdpt
 
Analysis insight about a Flyball dog competition team's performance
Analysis insight about a Flyball dog competition team's performanceAnalysis insight about a Flyball dog competition team's performance
Analysis insight about a Flyball dog competition team's performance
roli9797
 
一比一原版(UO毕业证)渥太华大学毕业证如何办理
一比一原版(UO毕业证)渥太华大学毕业证如何办理一比一原版(UO毕业证)渥太华大学毕业证如何办理
一比一原版(UO毕业证)渥太华大学毕业证如何办理
aqzctr7x
 
ViewShift: Hassle-free Dynamic Policy Enforcement for Every Data Lake
ViewShift: Hassle-free Dynamic Policy Enforcement for Every Data LakeViewShift: Hassle-free Dynamic Policy Enforcement for Every Data Lake
ViewShift: Hassle-free Dynamic Policy Enforcement for Every Data Lake
Walaa Eldin Moustafa
 
原版一比一弗林德斯大学毕业证(Flinders毕业证书)如何办理
原版一比一弗林德斯大学毕业证(Flinders毕业证书)如何办理原版一比一弗林德斯大学毕业证(Flinders毕业证书)如何办理
原版一比一弗林德斯大学毕业证(Flinders毕业证书)如何办理
a9qfiubqu
 
Experts live - Improving user adoption with AI
Experts live - Improving user adoption with AIExperts live - Improving user adoption with AI
Experts live - Improving user adoption with AI
jitskeb
 
Intelligence supported media monitoring in veterinary medicine
Intelligence supported media monitoring in veterinary medicineIntelligence supported media monitoring in veterinary medicine
Intelligence supported media monitoring in veterinary medicine
AndrzejJarynowski
 
End-to-end pipeline agility - Berlin Buzzwords 2024
End-to-end pipeline agility - Berlin Buzzwords 2024End-to-end pipeline agility - Berlin Buzzwords 2024
End-to-end pipeline agility - Berlin Buzzwords 2024
Lars Albertsson
 
"Financial Odyssey: Navigating Past Performance Through Diverse Analytical Lens"
"Financial Odyssey: Navigating Past Performance Through Diverse Analytical Lens""Financial Odyssey: Navigating Past Performance Through Diverse Analytical Lens"
"Financial Odyssey: Navigating Past Performance Through Diverse Analytical Lens"
sameer shah
 
4th Modern Marketing Reckoner by MMA Global India & Group M: 60+ experts on W...
4th Modern Marketing Reckoner by MMA Global India & Group M: 60+ experts on W...4th Modern Marketing Reckoner by MMA Global India & Group M: 60+ experts on W...
4th Modern Marketing Reckoner by MMA Global India & Group M: 60+ experts on W...
Social Samosa
 
Global Situational Awareness of A.I. and where its headed
Global Situational Awareness of A.I. and where its headedGlobal Situational Awareness of A.I. and where its headed
Global Situational Awareness of A.I. and where its headed
vikram sood
 
在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样
在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样
在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样
v7oacc3l
 
The Ipsos - AI - Monitor 2024 Report.pdf
The  Ipsos - AI - Monitor 2024 Report.pdfThe  Ipsos - AI - Monitor 2024 Report.pdf
The Ipsos - AI - Monitor 2024 Report.pdf
Social Samosa
 
06-12-2024-BudapestDataForum-BuildingReal-timePipelineswithFLaNK AIM
06-12-2024-BudapestDataForum-BuildingReal-timePipelineswithFLaNK AIM06-12-2024-BudapestDataForum-BuildingReal-timePipelineswithFLaNK AIM
06-12-2024-BudapestDataForum-BuildingReal-timePipelineswithFLaNK AIM
Timothy Spann
 
University of New South Wales degree offer diploma Transcript
University of New South Wales degree offer diploma TranscriptUniversity of New South Wales degree offer diploma Transcript
University of New South Wales degree offer diploma Transcript
soxrziqu
 
一比一原版(harvard毕业证书)哈佛大学毕业证如何办理
一比一原版(harvard毕业证书)哈佛大学毕业证如何办理一比一原版(harvard毕业证书)哈佛大学毕业证如何办理
一比一原版(harvard毕业证书)哈佛大学毕业证如何办理
taqyea
 
A presentation that explain the Power BI Licensing
A presentation that explain the Power BI LicensingA presentation that explain the Power BI Licensing
A presentation that explain the Power BI Licensing
AlessioFois2
 
一比一原版巴斯大学毕业证(Bath毕业证书)学历如何办理
一比一原版巴斯大学毕业证(Bath毕业证书)学历如何办理一比一原版巴斯大学毕业证(Bath毕业证书)学历如何办理
一比一原版巴斯大学毕业证(Bath毕业证书)学历如何办理
y3i0qsdzb
 
writing report business partner b1+ .pdf
writing report business partner b1+ .pdfwriting report business partner b1+ .pdf
writing report business partner b1+ .pdf
VyNguyen709676
 
Challenges of Nation Building-1.pptx with more important
Challenges of Nation Building-1.pptx with more importantChallenges of Nation Building-1.pptx with more important
Challenges of Nation Building-1.pptx with more important
Sm321
 

Recently uploaded (20)

一比一原版(UCSB文凭证书)圣芭芭拉分校毕业证如何办理
一比一原版(UCSB文凭证书)圣芭芭拉分校毕业证如何办理一比一原版(UCSB文凭证书)圣芭芭拉分校毕业证如何办理
一比一原版(UCSB文凭证书)圣芭芭拉分校毕业证如何办理
 
Analysis insight about a Flyball dog competition team's performance
Analysis insight about a Flyball dog competition team's performanceAnalysis insight about a Flyball dog competition team's performance
Analysis insight about a Flyball dog competition team's performance
 
一比一原版(UO毕业证)渥太华大学毕业证如何办理
一比一原版(UO毕业证)渥太华大学毕业证如何办理一比一原版(UO毕业证)渥太华大学毕业证如何办理
一比一原版(UO毕业证)渥太华大学毕业证如何办理
 
ViewShift: Hassle-free Dynamic Policy Enforcement for Every Data Lake
ViewShift: Hassle-free Dynamic Policy Enforcement for Every Data LakeViewShift: Hassle-free Dynamic Policy Enforcement for Every Data Lake
ViewShift: Hassle-free Dynamic Policy Enforcement for Every Data Lake
 
原版一比一弗林德斯大学毕业证(Flinders毕业证书)如何办理
原版一比一弗林德斯大学毕业证(Flinders毕业证书)如何办理原版一比一弗林德斯大学毕业证(Flinders毕业证书)如何办理
原版一比一弗林德斯大学毕业证(Flinders毕业证书)如何办理
 
Experts live - Improving user adoption with AI
Experts live - Improving user adoption with AIExperts live - Improving user adoption with AI
Experts live - Improving user adoption with AI
 
Intelligence supported media monitoring in veterinary medicine
Intelligence supported media monitoring in veterinary medicineIntelligence supported media monitoring in veterinary medicine
Intelligence supported media monitoring in veterinary medicine
 
End-to-end pipeline agility - Berlin Buzzwords 2024
End-to-end pipeline agility - Berlin Buzzwords 2024End-to-end pipeline agility - Berlin Buzzwords 2024
End-to-end pipeline agility - Berlin Buzzwords 2024
 
"Financial Odyssey: Navigating Past Performance Through Diverse Analytical Lens"
"Financial Odyssey: Navigating Past Performance Through Diverse Analytical Lens""Financial Odyssey: Navigating Past Performance Through Diverse Analytical Lens"
"Financial Odyssey: Navigating Past Performance Through Diverse Analytical Lens"
 
4th Modern Marketing Reckoner by MMA Global India & Group M: 60+ experts on W...
4th Modern Marketing Reckoner by MMA Global India & Group M: 60+ experts on W...4th Modern Marketing Reckoner by MMA Global India & Group M: 60+ experts on W...
4th Modern Marketing Reckoner by MMA Global India & Group M: 60+ experts on W...
 
Global Situational Awareness of A.I. and where its headed
Global Situational Awareness of A.I. and where its headedGlobal Situational Awareness of A.I. and where its headed
Global Situational Awareness of A.I. and where its headed
 
在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样
在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样
在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样
 
The Ipsos - AI - Monitor 2024 Report.pdf
The  Ipsos - AI - Monitor 2024 Report.pdfThe  Ipsos - AI - Monitor 2024 Report.pdf
The Ipsos - AI - Monitor 2024 Report.pdf
 
06-12-2024-BudapestDataForum-BuildingReal-timePipelineswithFLaNK AIM
06-12-2024-BudapestDataForum-BuildingReal-timePipelineswithFLaNK AIM06-12-2024-BudapestDataForum-BuildingReal-timePipelineswithFLaNK AIM
06-12-2024-BudapestDataForum-BuildingReal-timePipelineswithFLaNK AIM
 
University of New South Wales degree offer diploma Transcript
University of New South Wales degree offer diploma TranscriptUniversity of New South Wales degree offer diploma Transcript
University of New South Wales degree offer diploma Transcript
 
一比一原版(harvard毕业证书)哈佛大学毕业证如何办理
一比一原版(harvard毕业证书)哈佛大学毕业证如何办理一比一原版(harvard毕业证书)哈佛大学毕业证如何办理
一比一原版(harvard毕业证书)哈佛大学毕业证如何办理
 
A presentation that explain the Power BI Licensing
A presentation that explain the Power BI LicensingA presentation that explain the Power BI Licensing
A presentation that explain the Power BI Licensing
 
一比一原版巴斯大学毕业证(Bath毕业证书)学历如何办理
一比一原版巴斯大学毕业证(Bath毕业证书)学历如何办理一比一原版巴斯大学毕业证(Bath毕业证书)学历如何办理
一比一原版巴斯大学毕业证(Bath毕业证书)学历如何办理
 
writing report business partner b1+ .pdf
writing report business partner b1+ .pdfwriting report business partner b1+ .pdf
writing report business partner b1+ .pdf
 
Challenges of Nation Building-1.pptx with more important
Challenges of Nation Building-1.pptx with more importantChallenges of Nation Building-1.pptx with more important
Challenges of Nation Building-1.pptx with more important
 

Recursion.ppt

  • 1. Recursion CS 308 – Data Structures
  • 2. What is recursion? • Sometimes, the best way to solve a problem is by solving a smaller version of the exact same problem first • Recursion is a technique that solves a problem by solving a smaller problem of the same type
  • 3. 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; } }
  • 4. Problems defined recursively • There are many problems whose solution can be defined recursively Example: n factorial 1 if n = 0 n!= (recursive solution) (n-1)!*n if n > 0 1 if n = 0 n!= (closed form solution) 1*2*3*…*(n-1)*n if n > 0
  • 5. Coding the factorial function • Recursive implementation int Factorial(int n) { if (n==0) // base case return 1; else return n * Factorial(n-1); }
  • 6.
  • 7. 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; }
  • 8. 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 = n (k = 1), = 1 (k = n) 1 n
  • 9. 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)
  • 10.
  • 11. 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
  • 12. 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")
  • 13. 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?
  • 14. Recursive binary search • Non-recursive implementation template<class ItemType> void SortedType<ItemType>::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]; } }
  • 15. • 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)
  • 16. template<class ItemType> 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)
  • 17. template<class ItemType> void SortedType<ItemType>::RetrieveItem (ItemType& item, bool& found) { found = BinarySearch(info, item, 0, length-1); } Recursive binary search (cont’d)
  • 18. 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; }
  • 19. 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
  • 20. • 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.)
  • 21. 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; } }
  • 23. Recursive InsertItem (sorted list) location location location location
  • 24. • 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 < location->info, insert item as the first node in the current list • What is the general case? Insert(location->next, item) Recursive InsertItem (sorted list)
  • 25. template <class ItemType> void Insert(NodeType<ItemType>* &location, ItemType item) { if(location == NULL) || (item < location->info)) { // base cases NodeType<ItemType>* tempPtr = location; location = new NodeType<ItemType>; location->info = item; location->next = tempPtr; } else Insert(location->next, newItem); // general case } template <class ItemType> void SortedType<ItemType>::InsertItem(ItemType newItem) { Insert(listData, newItem); } Recursive InsertItem (sorted list)
  • 26. - No "predLoc" pointer is needed for insertion location
  • 27. Recursive DeleteItem (sorted list) location location
  • 28. • 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.)
  • 29. template <class ItemType> void Delete(NodeType<ItemType>* &location, ItemType item) { if(item == location->info)) { NodeType<ItemType>* tempPtr = location; location = location->next; delete tempPtr; } else Delete(location->next, item); } template <class ItemType> void SortedType<ItemType>::DeleteItem(ItemType item) { Delete(listData, item); } Recursive DeleteItem (sorted list) (cont.)
  • 30. Recursion can be very inefficient is some cases + = = = = = = + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 3 3 Comb (3, 1) 2 Comb (2, 1) 1 Comb (2, 2) Comb (3, 2) Comb (4,2) 2 Comb (2, 1) 1 Comb (2, 2) Comb (3, 2) 1 1 Comb (3, 3) Comb (4, 3) Comb (5, 3) 2 Comb (2, 1) 1 Comb (2, 2) Comb (3, 2) 1 1 Comb (3, 3) Comb (4, 3) 1 1 1 Comb (4, 4) Comb (5, 4) Comb (6,4) 15
  • 31. 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