SlideShare a Scribd company logo
1 of 12
Recursion
Recursion
• In mathematics, we often say that a recursive solution is a solution such that f(xk) depends on
some of f(xk-1), f(xk-2),...f(x1), and f(x0)
• A usable recursive solution usually has the following characteristics
• –A base case. This is one which is easily calculated. It also prevents infinite loops!
• –A recursive case. This is the case in which the function “calls itself” in order to reduce the
calculations to the base case.
Simple problems solved recursively
• In math class we learned that 1+2+3+...+n = n*(n+1)/2
• For example, 1+2+...+10 = 10*11/2 = 55
• It is also easy to find the sum iteratively by an O(n) algorithm
int sum=0;
for i = 1 to n
sum=sum + i
• We can also solve this problem by recursion.
• Recursion to find 1 + 2 + + … + n
public sum(n)
if n == 1, sum =1
if n > 1, sum = n +sum(n-1)
Identify the base case
Identify the recursive case
• Example: sum(5) = 5 + sum(4)
= 5+4+sum(3) =9 +sum(3)
=9 +3+sum(2)
= 12 = 12 = 14 = 14
+sum(2)= +2+sum(1)
• On the next slide, we implement the recursive function in Java
• Recursive sum used to find the sum to n for n = 1, 2, ..., 10
• Note there is NO reason to compute the sums this way. This example is purely for illustration of
recursion.
n!
• From math class, we know that n! = n*(n-1)*(n-2)*...*3*2*1
3! = 3*2*1 = 6
5!= 5*4*3 *2 *1
• It is easy to compute n! iteratively
int prod = 1;
for i=2 to n
prod = prod * i
Recursive n!
• We easily observe that there is a recursive definition of n!
n! = n*(n-1) !
• For example 4 ! = 4*3*2*1 = 4*(3*2*1) = 4 * 3!
• This prompts the following function
int nfact (int n)
if n == 0 or n ==1
return 1
else
return n * nfact (n-1)
Fibonacci Numbers
• The Fibonacci number sequence:
1, 1, 2, 3, 5, 8, 13, ....
• The first two elements of the sequence are both 1
• Subsequent elements are formed by adding the two before it.
• Recursive Fibonacci
fib (n)
if (n==1 or n==0)
return 1;
else
return fib (n-1) + fib (n-2)
Recursive & Iterative Fibonacci
Notice how short and compact the recursive
version is.
Remarks about recursion
• In general
• A recursive solution is simpler to code than an iterative solution
• Some problems are so difficult that recursion may be the best solution
• Iterative solutions are often faster than recursive solutions
Recursive search
• It is very simple to write an iterative search to determine if a given value (toFind) is in an array
for i = 0 to the array length -1
if array[i] = to_find
return true
End i loop
Return false
• When we do it recursively
• If the array has length 1, we return true if the single element and toFind are the same
• If not
• we check the first element and return true if it and toFind are equal
• Otherwise, we repeat the search on the remainder of the array
Recursion

More Related Content

What's hot

Discreate time system and z transform
Discreate time system and z transformDiscreate time system and z transform
Discreate time system and z transformVIKAS KUMAR MANJHI
 
レポート深層学習前編
レポート深層学習前編レポート深層学習前編
レポート深層学習前編ssuser9d95b3
 
Hyperbolictangent exercise
Hyperbolictangent exerciseHyperbolictangent exercise
Hyperbolictangent exerciseritahani
 
PowerPoint Presentation
PowerPoint PresentationPowerPoint Presentation
PowerPoint Presentationbutest
 
Applications of Z transform
Applications of Z transformApplications of Z transform
Applications of Z transformAakankshaR
 

What's hot (9)

Discreate time system and z transform
Discreate time system and z transformDiscreate time system and z transform
Discreate time system and z transform
 
レポート深層学習前編
レポート深層学習前編レポート深層学習前編
レポート深層学習前編
 
Z transform
 Z transform Z transform
Z transform
 
21 2 ztransform
21 2 ztransform21 2 ztransform
21 2 ztransform
 
Hyperbolictangent exercise
Hyperbolictangent exerciseHyperbolictangent exercise
Hyperbolictangent exercise
 
Advance logic
Advance logicAdvance logic
Advance logic
 
PowerPoint Presentation
PowerPoint PresentationPowerPoint Presentation
PowerPoint Presentation
 
21 5 ztransform
21 5 ztransform21 5 ztransform
21 5 ztransform
 
Applications of Z transform
Applications of Z transformApplications of Z transform
Applications of Z transform
 

Similar to Recursion

lecture4-recursion.pptx
lecture4-recursion.pptxlecture4-recursion.pptx
lecture4-recursion.pptxLizhen Shi
 
Copy of y16 02-2119divide-and-conquer
Copy of y16 02-2119divide-and-conquerCopy of y16 02-2119divide-and-conquer
Copy of y16 02-2119divide-and-conquerJoepang2015
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programmingGopi Saiteja
 
1 chapter1 introduction
1 chapter1 introduction1 chapter1 introduction
1 chapter1 introductionSSE_AndyLi
 
Lecture 5 6_7 - divide and conquer and method of solving recurrences
Lecture 5 6_7 - divide and conquer and method of solving recurrencesLecture 5 6_7 - divide and conquer and method of solving recurrences
Lecture 5 6_7 - divide and conquer and method of solving recurrencesjayavignesh86
 
Sure interview algorithm-1103
Sure interview algorithm-1103Sure interview algorithm-1103
Sure interview algorithm-1103Sure Interview
 
Lecture 3 complexity
Lecture 3 complexityLecture 3 complexity
Lecture 3 complexityMadhu Niket
 
Ch01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluitonCh01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluitonshin
 
Skiena algorithm 2007 lecture16 introduction to dynamic programming
Skiena algorithm 2007 lecture16 introduction to dynamic programmingSkiena algorithm 2007 lecture16 introduction to dynamic programming
Skiena algorithm 2007 lecture16 introduction to dynamic programmingzukun
 

Similar to Recursion (20)

Recursion.pdf
Recursion.pdfRecursion.pdf
Recursion.pdf
 
Recursion
RecursionRecursion
Recursion
 
6-Python-Recursion.pdf
6-Python-Recursion.pdf6-Python-Recursion.pdf
6-Python-Recursion.pdf
 
lecture4-recursion.pptx
lecture4-recursion.pptxlecture4-recursion.pptx
lecture4-recursion.pptx
 
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
 
Dynamic programing
Dynamic programingDynamic programing
Dynamic programing
 
Copy of y16 02-2119divide-and-conquer
Copy of y16 02-2119divide-and-conquerCopy of y16 02-2119divide-and-conquer
Copy of y16 02-2119divide-and-conquer
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Sec4
Sec4Sec4
Sec4
 
DS & Algo 2 - Recursion
DS & Algo 2 - RecursionDS & Algo 2 - Recursion
DS & Algo 2 - Recursion
 
1 chapter1 introduction
1 chapter1 introduction1 chapter1 introduction
1 chapter1 introduction
 
Dynamic programming Basics
Dynamic programming BasicsDynamic programming Basics
Dynamic programming Basics
 
Recursion
RecursionRecursion
Recursion
 
Lecture 5 6_7 - divide and conquer and method of solving recurrences
Lecture 5 6_7 - divide and conquer and method of solving recurrencesLecture 5 6_7 - divide and conquer and method of solving recurrences
Lecture 5 6_7 - divide and conquer and method of solving recurrences
 
RecursionWeek8.ppt
RecursionWeek8.pptRecursionWeek8.ppt
RecursionWeek8.ppt
 
Sure interview algorithm-1103
Sure interview algorithm-1103Sure interview algorithm-1103
Sure interview algorithm-1103
 
Lecture 3 complexity
Lecture 3 complexityLecture 3 complexity
Lecture 3 complexity
 
Recursion
RecursionRecursion
Recursion
 
Ch01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluitonCh01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluiton
 
Skiena algorithm 2007 lecture16 introduction to dynamic programming
Skiena algorithm 2007 lecture16 introduction to dynamic programmingSkiena algorithm 2007 lecture16 introduction to dynamic programming
Skiena algorithm 2007 lecture16 introduction to dynamic programming
 

More from SAGARDAVE29

Graphical User Interface (GUI)
Graphical User Interface (GUI)Graphical User Interface (GUI)
Graphical User Interface (GUI)SAGARDAVE29
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVASAGARDAVE29
 
Exception Handling
Exception HandlingException Handling
Exception HandlingSAGARDAVE29
 
JAVA Multithreading
JAVA MultithreadingJAVA Multithreading
JAVA MultithreadingSAGARDAVE29
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVASAGARDAVE29
 
Exception handling
Exception handlingException handling
Exception handlingSAGARDAVE29
 
More oop in java
More oop in javaMore oop in java
More oop in javaSAGARDAVE29
 
Coding Style & Tips for JAVA
Coding Style & Tips for JAVACoding Style & Tips for JAVA
Coding Style & Tips for JAVASAGARDAVE29
 
Some Important Methods in JAVA
Some Important Methods in JAVASome Important Methods in JAVA
Some Important Methods in JAVASAGARDAVE29
 
Inheritance & Polymorphism
Inheritance & PolymorphismInheritance & Polymorphism
Inheritance & PolymorphismSAGARDAVE29
 

More from SAGARDAVE29 (12)

Graphical User Interface (GUI)
Graphical User Interface (GUI)Graphical User Interface (GUI)
Graphical User Interface (GUI)
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
JAVA Multithreading
JAVA MultithreadingJAVA Multithreading
JAVA Multithreading
 
Stack & Queue
Stack & QueueStack & Queue
Stack & Queue
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Exception handling
Exception handlingException handling
Exception handling
 
More oop in java
More oop in javaMore oop in java
More oop in java
 
Coding Style & Tips for JAVA
Coding Style & Tips for JAVACoding Style & Tips for JAVA
Coding Style & Tips for JAVA
 
Some Important Methods in JAVA
Some Important Methods in JAVASome Important Methods in JAVA
Some Important Methods in JAVA
 
Inheritance & Polymorphism
Inheritance & PolymorphismInheritance & Polymorphism
Inheritance & Polymorphism
 

Recently uploaded

Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 

Recently uploaded (20)

Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 

Recursion

  • 2. Recursion • In mathematics, we often say that a recursive solution is a solution such that f(xk) depends on some of f(xk-1), f(xk-2),...f(x1), and f(x0) • A usable recursive solution usually has the following characteristics • –A base case. This is one which is easily calculated. It also prevents infinite loops! • –A recursive case. This is the case in which the function “calls itself” in order to reduce the calculations to the base case.
  • 3. Simple problems solved recursively • In math class we learned that 1+2+3+...+n = n*(n+1)/2 • For example, 1+2+...+10 = 10*11/2 = 55 • It is also easy to find the sum iteratively by an O(n) algorithm int sum=0; for i = 1 to n sum=sum + i • We can also solve this problem by recursion.
  • 4. • Recursion to find 1 + 2 + + … + n public sum(n) if n == 1, sum =1 if n > 1, sum = n +sum(n-1) Identify the base case Identify the recursive case • Example: sum(5) = 5 + sum(4) = 5+4+sum(3) =9 +sum(3) =9 +3+sum(2) = 12 = 12 = 14 = 14 +sum(2)= +2+sum(1) • On the next slide, we implement the recursive function in Java
  • 5. • Recursive sum used to find the sum to n for n = 1, 2, ..., 10 • Note there is NO reason to compute the sums this way. This example is purely for illustration of recursion.
  • 6. n! • From math class, we know that n! = n*(n-1)*(n-2)*...*3*2*1 3! = 3*2*1 = 6 5!= 5*4*3 *2 *1 • It is easy to compute n! iteratively int prod = 1; for i=2 to n prod = prod * i
  • 7. Recursive n! • We easily observe that there is a recursive definition of n! n! = n*(n-1) ! • For example 4 ! = 4*3*2*1 = 4*(3*2*1) = 4 * 3! • This prompts the following function int nfact (int n) if n == 0 or n ==1 return 1 else return n * nfact (n-1)
  • 8. Fibonacci Numbers • The Fibonacci number sequence: 1, 1, 2, 3, 5, 8, 13, .... • The first two elements of the sequence are both 1 • Subsequent elements are formed by adding the two before it. • Recursive Fibonacci fib (n) if (n==1 or n==0) return 1; else return fib (n-1) + fib (n-2)
  • 9. Recursive & Iterative Fibonacci Notice how short and compact the recursive version is.
  • 10. Remarks about recursion • In general • A recursive solution is simpler to code than an iterative solution • Some problems are so difficult that recursion may be the best solution • Iterative solutions are often faster than recursive solutions
  • 11. Recursive search • It is very simple to write an iterative search to determine if a given value (toFind) is in an array for i = 0 to the array length -1 if array[i] = to_find return true End i loop Return false • When we do it recursively • If the array has length 1, we return true if the single element and toFind are the same • If not • we check the first element and return true if it and toFind are equal • Otherwise, we repeat the search on the remainder of the array