SlideShare ist ein Scribd-Unternehmen logo
1 von 5
Downloaden Sie, um offline zu lesen
Recursion lecture in Java
Recursively breaking down a problem into two or more sub-problems of the
same (or related) type, until these become simple enough to be solved directly.
The solutions to the sub-problems are then combined to give a solution to the
original problem.
Top-Down Design
Cleaning apartment/house.
Example
Divide and Conquer Algorithm
Many divide and conquer type algorithms can be implemented as recursive
functions.
Condition that leads to a recursive method returning without making another
recursive call.
Stops the recursion.
Solution to this case is simple enough to solve directly.
Base case.
Calls itself to solve smaller sub-problems.
May combine the results of the sub-problems.
Properties of recursive functions
Recursive methods
/**
* This is the recursive form of arithmetic series
* x = x + (x-1) + (x-2) + .. + 0
*/
public class ArthmeticSeries {
public static void main(String[] args) {
int sum = arthmeticSeries(2);
System.out.println(sum);
}
private static int arthmeticSeries(int x) {
//base case.
if (x == 0)
return 0;
Example: Arithmetic Series
//base case.
if (x == 0)
return 0;
//recursive case.
return x + arthmeticSeries(x - 1);
}
}
Example: cafeteria plates.
A stack is a FIFO data structure.
Each method call produces a stack frame (like a plate).
Information about the method.
Method arguments.
Information on how to return to the caller.
Each frame consists of:
What does recursion look like on the call stack?
The Fibonacci sequence a(1), a(2), a(3), ..., a(n), ... is defined by
a(1) =1
a(2) = 1
a(n) = a(n-1) + a(n-2)
, for all n > 2
This generates the sequence:
1, 1, 2, 3, 5, 8, 13, 21, ...
fibonacci(7) == 13
public class Fibonacci {
public static void main(String[] args) {
int num = fib(7);
System.out.println(num);
}
private static int fib(int x) {
if (x == 0)
return 0;
if (x == 1)
return 1;
Example: Fibonacci sequence
return 0;
if (x == 1)
return 1;
return fib(x - 1) + fib(x - 2);
}
}
public class BinarySearch {
public static void main(String[] args) {
int myArray[] = {41, 62, 77, 80, 85, 92, 104, 211, 400};
int pos = binsearch(myArray, 0, myArray.length, 62);
System.out.println(pos);
pos = binsearch(myArray, 0, myArray.length, 97);
System.out.println(pos);
}
private static int binsearch(int arr[], int start, int end, int val)
{
if ( start > end ) //if empty.
return -1; //not found.
int mid = (start + end) / 2;
if ( arr[ mid ] == val )
return mid; //found it!
else if ( arr[ mid ] < val )
return binsearch(arr, mid + 1, end, val);
else //arr[ mid ] > val
return binsearch(arr, start, mid - 1, val);
}
}
ex: 41 62 77 80 85 92 104 211 400
- search for 62
- check index 4 ((0+8)/2)
- (0+3)/2
- report found
- search for 97
- 97 > 85
- (5+8)/2 = 6
- 97 < 104
- (5+5)/2 = 5
- 97 > 92
Example: Binary Search
- (5+8)/2 = 6
- 97 < 104
- (5+5)/2 = 5
- 97 > 92
- use low and high index values to find that there are no more values to
search
Consider the sorting problem. That is, given a list of comparable
items (say an array of {bf int}s) in arbitrary order, rearrange that list
of items so that they are in {it non-decreasing} order. For example, say
you have an array of {bf int}s: $langle 38, 27, 43, 3, 9, 82, 10
rangle$. A sorted version of this array would be $langle 3, 9, 10, 27,
38, 43, 82 rangle$. Next, consider an efficient, divide and conquer
algorithm that can be used to {it recursively} solve the sorting problem
as follows:
begin{enumerate}
item Divide the unsorted list into two sublists of about half the
size.
item Divide each of the two sublists recursively until we have list
sizes of length $1$, in which case the list itself is returned
(after all, a list containing only $1$ element is always considered
sorted!).
item Merge the two sublists back into one sorted list.
end{enumerate}
Suppose now that you had the following function available to you:
begin{lstlisting}{}
void merge(Item arr[], const int& left, const int& right,
const int& pivot);
end{lstlisting}
that combines two {bf sorted} sub-arrays of {tt arr} (i.e., the inclusive
intervals [{tt left}, {tt pivot}] and [{tt pivot}$+1$, {tt right}]) to a
underline{single} {bf sorted} array. The result of this {it combined},
sorted array is stored back into {tt arr} to form a single, sorted array
whose valid elements are contained in the interval [{tt left}, {tt right}].
{tt Item} refers to a type (possibly through use of a {bf typedef}) whose
members are comparable (e.g., {bf int}).
/*
* 'a' is an array of 'Items' whose valid elements are between 'start' and 'end',
* inclusively. 'mid' is the position in 'a' in which to divide the array.
*/
void mergesort(Item a[], const int& start, const int& end, const int& mid) {
if ( start >= end ) //the array is either empty or contains a single element.
return; //sorting problem already solved. Nothing to do.
Example: Mergesort
if ( start >= end ) //the array is either empty or contains a single element.
return; //sorting problem already solved. Nothing to do.
//sort the left portion of the array.
mergesort(a, start, mid, (start + mid) / 2);
//sort the right portion of the array
mergesort(a, mid + 1, end, (mid + 1 + end) / 2);
//combined the two sorted array portions in a single sorted array.
merge(a, start, end, mid);
}

Weitere ähnliche Inhalte

Was ist angesagt?

Set data structure
Set data structure Set data structure
Set data structure
Tech_MX
 

Was ist angesagt? (20)

Array data structure
Array data structureArray data structure
Array data structure
 
Arrays
ArraysArrays
Arrays
 
Set data structure
Set data structure Set data structure
Set data structure
 
2 data structure in R
2 data structure in R2 data structure in R
2 data structure in R
 
Row major and column major in 2 d
Row major and column major in 2 dRow major and column major in 2 d
Row major and column major in 2 d
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Unit 4 tree
Unit 4   treeUnit 4   tree
Unit 4 tree
 
Array
ArrayArray
Array
 
2 data types and operators in r
2 data types and operators in r2 data types and operators in r
2 data types and operators in r
 
Array ppt
Array pptArray ppt
Array ppt
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
Array
ArrayArray
Array
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Array
ArrayArray
Array
 
Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)
 
Array
ArrayArray
Array
 
Arrays In C++
Arrays In C++Arrays In C++
Arrays In C++
 
Files,blocks and functions in R
Files,blocks and functions in RFiles,blocks and functions in R
Files,blocks and functions in R
 
Arrays
ArraysArrays
Arrays
 
ARRAY
ARRAYARRAY
ARRAY
 

Andere mochten auch

Ap Power Point Chpt9
Ap Power Point Chpt9Ap Power Point Chpt9
Ap Power Point Chpt9
dplunkett
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2
dplunkett
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
dplunkett
 
Ap Power Point Chpt8
Ap Power Point Chpt8Ap Power Point Chpt8
Ap Power Point Chpt8
dplunkett
 
Ap Power Point Chpt3 B
Ap Power Point Chpt3 BAp Power Point Chpt3 B
Ap Power Point Chpt3 B
dplunkett
 
Ap Power Point Chpt3
Ap Power Point Chpt3Ap Power Point Chpt3
Ap Power Point Chpt3
dplunkett
 
Ap Power Point Chpt7
Ap Power Point Chpt7Ap Power Point Chpt7
Ap Power Point Chpt7
dplunkett
 
Ap Power Point Chpt5
Ap Power Point Chpt5Ap Power Point Chpt5
Ap Power Point Chpt5
dplunkett
 
Ap Power Point Chpt6
Ap Power Point Chpt6Ap Power Point Chpt6
Ap Power Point Chpt6
dplunkett
 
Ap Power Point Chpt1
Ap Power Point Chpt1Ap Power Point Chpt1
Ap Power Point Chpt1
dplunkett
 

Andere mochten auch (20)

Lecture 4 recursion
Lecture 4    recursionLecture 4    recursion
Lecture 4 recursion
 
Ap Power Point Chpt9
Ap Power Point Chpt9Ap Power Point Chpt9
Ap Power Point Chpt9
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
 
First Principles Of Cs Instruction
First Principles Of Cs InstructionFirst Principles Of Cs Instruction
First Principles Of Cs Instruction
 
Ap Power Point Chpt8
Ap Power Point Chpt8Ap Power Point Chpt8
Ap Power Point Chpt8
 
Ap Power Point Chpt3 B
Ap Power Point Chpt3 BAp Power Point Chpt3 B
Ap Power Point Chpt3 B
 
Ap Power Point Chpt3
Ap Power Point Chpt3Ap Power Point Chpt3
Ap Power Point Chpt3
 
Ap Power Point Chpt7
Ap Power Point Chpt7Ap Power Point Chpt7
Ap Power Point Chpt7
 
JavaYDL20
JavaYDL20JavaYDL20
JavaYDL20
 
Ap Power Point Chpt5
Ap Power Point Chpt5Ap Power Point Chpt5
Ap Power Point Chpt5
 
Ap Power Point Chpt6
Ap Power Point Chpt6Ap Power Point Chpt6
Ap Power Point Chpt6
 
Ap Power Point Chpt1
Ap Power Point Chpt1Ap Power Point Chpt1
Ap Power Point Chpt1
 
Internet principles of operation
Internet principles of operationInternet principles of operation
Internet principles of operation
 
Recursion
RecursionRecursion
Recursion
 
Recursion
RecursionRecursion
Recursion
 
Recursion
RecursionRecursion
Recursion
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Recursion
RecursionRecursion
Recursion
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In Java
 

Ähnlich wie Recursion Lecture in Java

Underscore.js
Underscore.jsUnderscore.js
Underscore.js
timourian
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 

Ähnlich wie Recursion Lecture in Java (20)

Introduction to R
Introduction to RIntroduction to R
Introduction to R
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
 
Statistics lab 1
Statistics lab 1Statistics lab 1
Statistics lab 1
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
Functional object
Functional objectFunctional object
Functional object
 
A brief introduction to apply functions
A brief introduction to apply functionsA brief introduction to apply functions
A brief introduction to apply functions
 
Computer programming 2 Lesson 13
Computer programming 2  Lesson 13Computer programming 2  Lesson 13
Computer programming 2 Lesson 13
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
 
Rcommands-for those who interested in R.
Rcommands-for those who interested in R.Rcommands-for those who interested in R.
Rcommands-for those who interested in R.
 
Scala collection
Scala collectionScala collection
Scala collection
 
Loops and functions in r
Loops and functions in rLoops and functions in r
Loops and functions in r
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
C++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptxC++ STL (quickest way to learn, even for absolute beginners).pptx
C++ STL (quickest way to learn, even for absolute beginners).pptx
 
Basic R Data Manipulation
Basic R Data ManipulationBasic R Data Manipulation
Basic R Data Manipulation
 
R교육1
R교육1R교육1
R교육1
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 
A limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced RubyA limited guide to intermediate and advanced Ruby
A limited guide to intermediate and advanced Ruby
 
Collections
CollectionsCollections
Collections
 
Practical cats
Practical catsPractical cats
Practical cats
 

Mehr von Raffi Khatchadourian

Towards Safe Automated Refactoring of Imperative Deep Learning Programs to Gr...
Towards Safe Automated Refactoring of Imperative Deep Learning Programs to Gr...Towards Safe Automated Refactoring of Imperative Deep Learning Programs to Gr...
Towards Safe Automated Refactoring of Imperative Deep Learning Programs to Gr...
Raffi Khatchadourian
 
Automated Evolution of Feature Logging Statement Levels Using Git Histories a...
Automated Evolution of Feature Logging Statement Levels Using Git Histories a...Automated Evolution of Feature Logging Statement Levels Using Git Histories a...
Automated Evolution of Feature Logging Statement Levels Using Git Histories a...
Raffi Khatchadourian
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
Actor Concurrency Bugs: A Comprehensive Study on Symptoms, Root Causes, API U...
Actor Concurrency Bugs: A Comprehensive Study on Symptoms, Root Causes, API U...Actor Concurrency Bugs: A Comprehensive Study on Symptoms, Root Causes, API U...
Actor Concurrency Bugs: A Comprehensive Study on Symptoms, Root Causes, API U...
Raffi Khatchadourian
 
An Empirical Study of Refactorings and Technical Debt in Machine Learning Sys...
An Empirical Study of Refactorings and Technical Debt in Machine Learning Sys...An Empirical Study of Refactorings and Technical Debt in Machine Learning Sys...
An Empirical Study of Refactorings and Technical Debt in Machine Learning Sys...
Raffi Khatchadourian
 
Automated Evolution of Feature Logging Statement Levels Using Git Histories a...
Automated Evolution of Feature Logging Statement Levels Using Git Histories a...Automated Evolution of Feature Logging Statement Levels Using Git Histories a...
Automated Evolution of Feature Logging Statement Levels Using Git Histories a...
Raffi Khatchadourian
 
Safe Automated Refactoring for Intelligent Parallelization of Java 8 Streams
Safe Automated Refactoring for Intelligent Parallelization of Java 8 StreamsSafe Automated Refactoring for Intelligent Parallelization of Java 8 Streams
Safe Automated Refactoring for Intelligent Parallelization of Java 8 Streams
Raffi Khatchadourian
 
Safe Automated Refactoring for Intelligent Parallelization of Java 8 Streams
Safe Automated Refactoring for Intelligent Parallelization of Java 8 StreamsSafe Automated Refactoring for Intelligent Parallelization of Java 8 Streams
Safe Automated Refactoring for Intelligent Parallelization of Java 8 Streams
Raffi Khatchadourian
 
Safe Automated Refactoring for Intelligent Parallelization of Java 8 Streams ...
Safe Automated Refactoring for Intelligent Parallelization of Java 8 Streams ...Safe Automated Refactoring for Intelligent Parallelization of Java 8 Streams ...
Safe Automated Refactoring for Intelligent Parallelization of Java 8 Streams ...
Raffi Khatchadourian
 
A Tool for Optimizing Java 8 Stream Software via Automated Refactoring
A Tool for Optimizing Java 8 Stream Software via Automated RefactoringA Tool for Optimizing Java 8 Stream Software via Automated Refactoring
A Tool for Optimizing Java 8 Stream Software via Automated Refactoring
Raffi Khatchadourian
 
Proactive Empirical Assessment of New Language Feature Adoption via Automated...
Proactive Empirical Assessment of New Language Feature Adoption via Automated...Proactive Empirical Assessment of New Language Feature Adoption via Automated...
Proactive Empirical Assessment of New Language Feature Adoption via Automated...
Raffi Khatchadourian
 

Mehr von Raffi Khatchadourian (20)

Towards Safe Automated Refactoring of Imperative Deep Learning Programs to Gr...
Towards Safe Automated Refactoring of Imperative Deep Learning Programs to Gr...Towards Safe Automated Refactoring of Imperative Deep Learning Programs to Gr...
Towards Safe Automated Refactoring of Imperative Deep Learning Programs to Gr...
 
Automated Evolution of Feature Logging Statement Levels Using Git Histories a...
Automated Evolution of Feature Logging Statement Levels Using Git Histories a...Automated Evolution of Feature Logging Statement Levels Using Git Histories a...
Automated Evolution of Feature Logging Statement Levels Using Git Histories a...
 
A Tool for Rejuvenating Feature Logging Levels via Git Histories and Degree o...
A Tool for Rejuvenating Feature Logging Levels via Git Histories and Degree o...A Tool for Rejuvenating Feature Logging Levels via Git Histories and Degree o...
A Tool for Rejuvenating Feature Logging Levels via Git Histories and Degree o...
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
 
Actor Concurrency Bugs: A Comprehensive Study on Symptoms, Root Causes, API U...
Actor Concurrency Bugs: A Comprehensive Study on Symptoms, Root Causes, API U...Actor Concurrency Bugs: A Comprehensive Study on Symptoms, Root Causes, API U...
Actor Concurrency Bugs: A Comprehensive Study on Symptoms, Root Causes, API U...
 
An Empirical Study of Refactorings and Technical Debt in Machine Learning Sys...
An Empirical Study of Refactorings and Technical Debt in Machine Learning Sys...An Empirical Study of Refactorings and Technical Debt in Machine Learning Sys...
An Empirical Study of Refactorings and Technical Debt in Machine Learning Sys...
 
Automated Evolution of Feature Logging Statement Levels Using Git Histories a...
Automated Evolution of Feature Logging Statement Levels Using Git Histories a...Automated Evolution of Feature Logging Statement Levels Using Git Histories a...
Automated Evolution of Feature Logging Statement Levels Using Git Histories a...
 
An Empirical Study on the Use and Misuse of Java 8 Streams
An Empirical Study on the Use and Misuse of Java 8 StreamsAn Empirical Study on the Use and Misuse of Java 8 Streams
An Empirical Study on the Use and Misuse of Java 8 Streams
 
Safe Automated Refactoring for Intelligent Parallelization of Java 8 Streams
Safe Automated Refactoring for Intelligent Parallelization of Java 8 StreamsSafe Automated Refactoring for Intelligent Parallelization of Java 8 Streams
Safe Automated Refactoring for Intelligent Parallelization of Java 8 Streams
 
Safe Automated Refactoring for Intelligent Parallelization of Java 8 Streams
Safe Automated Refactoring for Intelligent Parallelization of Java 8 StreamsSafe Automated Refactoring for Intelligent Parallelization of Java 8 Streams
Safe Automated Refactoring for Intelligent Parallelization of Java 8 Streams
 
A Brief Introduction to Type Constraints
A Brief Introduction to Type ConstraintsA Brief Introduction to Type Constraints
A Brief Introduction to Type Constraints
 
Safe Automated Refactoring for Intelligent Parallelization of Java 8 Streams ...
Safe Automated Refactoring for Intelligent Parallelization of Java 8 Streams ...Safe Automated Refactoring for Intelligent Parallelization of Java 8 Streams ...
Safe Automated Refactoring for Intelligent Parallelization of Java 8 Streams ...
 
A Tool for Optimizing Java 8 Stream Software via Automated Refactoring
A Tool for Optimizing Java 8 Stream Software via Automated RefactoringA Tool for Optimizing Java 8 Stream Software via Automated Refactoring
A Tool for Optimizing Java 8 Stream Software via Automated Refactoring
 
Porting the NetBeans Java 8 Enhanced For Loop Lambda Expression Refactoring t...
Porting the NetBeans Java 8 Enhanced For Loop Lambda Expression Refactoring t...Porting the NetBeans Java 8 Enhanced For Loop Lambda Expression Refactoring t...
Porting the NetBeans Java 8 Enhanced For Loop Lambda Expression Refactoring t...
 
Towards Safe Refactoring for Intelligent Parallelization of Java 8 Streams
Towards Safe Refactoring for Intelligent Parallelization of Java 8 StreamsTowards Safe Refactoring for Intelligent Parallelization of Java 8 Streams
Towards Safe Refactoring for Intelligent Parallelization of Java 8 Streams
 
Proactive Empirical Assessment of New Language Feature Adoption via Automated...
Proactive Empirical Assessment of New Language Feature Adoption via Automated...Proactive Empirical Assessment of New Language Feature Adoption via Automated...
Proactive Empirical Assessment of New Language Feature Adoption via Automated...
 
Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Defaultification Refactoring: A Tool for Automatically Converting Java Method...Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Defaultification Refactoring: A Tool for Automatically Converting Java Method...
 
Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Defaultification Refactoring: A Tool for Automatically Converting Java Method...Defaultification Refactoring: A Tool for Automatically Converting Java Method...
Defaultification Refactoring: A Tool for Automatically Converting Java Method...
 
Automated Refactoring of Legacy Java Software to Default Methods Talk at ICSE...
Automated Refactoring of Legacy Java Software to Default Methods Talk at ICSE...Automated Refactoring of Legacy Java Software to Default Methods Talk at ICSE...
Automated Refactoring of Legacy Java Software to Default Methods Talk at ICSE...
 
Poster on Automated Refactoring of Legacy Java Software to Default Methods
Poster on Automated Refactoring of Legacy Java Software to Default MethodsPoster on Automated Refactoring of Legacy Java Software to Default Methods
Poster on Automated Refactoring of Legacy Java Software to Default Methods
 

Kürzlich hochgeladen

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 

Kürzlich hochgeladen (20)

Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 

Recursion Lecture in Java

  • 1. Recursion lecture in Java Recursively breaking down a problem into two or more sub-problems of the same (or related) type, until these become simple enough to be solved directly. The solutions to the sub-problems are then combined to give a solution to the original problem. Top-Down Design Cleaning apartment/house. Example Divide and Conquer Algorithm Many divide and conquer type algorithms can be implemented as recursive functions. Condition that leads to a recursive method returning without making another recursive call. Stops the recursion. Solution to this case is simple enough to solve directly. Base case. Calls itself to solve smaller sub-problems. May combine the results of the sub-problems. Properties of recursive functions Recursive methods /** * This is the recursive form of arithmetic series * x = x + (x-1) + (x-2) + .. + 0 */ public class ArthmeticSeries { public static void main(String[] args) { int sum = arthmeticSeries(2); System.out.println(sum); } private static int arthmeticSeries(int x) { //base case. if (x == 0) return 0; Example: Arithmetic Series
  • 2. //base case. if (x == 0) return 0; //recursive case. return x + arthmeticSeries(x - 1); } } Example: cafeteria plates. A stack is a FIFO data structure. Each method call produces a stack frame (like a plate). Information about the method. Method arguments. Information on how to return to the caller. Each frame consists of: What does recursion look like on the call stack? The Fibonacci sequence a(1), a(2), a(3), ..., a(n), ... is defined by a(1) =1 a(2) = 1 a(n) = a(n-1) + a(n-2) , for all n > 2 This generates the sequence: 1, 1, 2, 3, 5, 8, 13, 21, ... fibonacci(7) == 13 public class Fibonacci { public static void main(String[] args) { int num = fib(7); System.out.println(num); } private static int fib(int x) { if (x == 0) return 0; if (x == 1) return 1; Example: Fibonacci sequence
  • 3. return 0; if (x == 1) return 1; return fib(x - 1) + fib(x - 2); } } public class BinarySearch { public static void main(String[] args) { int myArray[] = {41, 62, 77, 80, 85, 92, 104, 211, 400}; int pos = binsearch(myArray, 0, myArray.length, 62); System.out.println(pos); pos = binsearch(myArray, 0, myArray.length, 97); System.out.println(pos); } private static int binsearch(int arr[], int start, int end, int val) { if ( start > end ) //if empty. return -1; //not found. int mid = (start + end) / 2; if ( arr[ mid ] == val ) return mid; //found it! else if ( arr[ mid ] < val ) return binsearch(arr, mid + 1, end, val); else //arr[ mid ] > val return binsearch(arr, start, mid - 1, val); } } ex: 41 62 77 80 85 92 104 211 400 - search for 62 - check index 4 ((0+8)/2) - (0+3)/2 - report found - search for 97 - 97 > 85 - (5+8)/2 = 6 - 97 < 104 - (5+5)/2 = 5 - 97 > 92 Example: Binary Search
  • 4. - (5+8)/2 = 6 - 97 < 104 - (5+5)/2 = 5 - 97 > 92 - use low and high index values to find that there are no more values to search Consider the sorting problem. That is, given a list of comparable items (say an array of {bf int}s) in arbitrary order, rearrange that list of items so that they are in {it non-decreasing} order. For example, say you have an array of {bf int}s: $langle 38, 27, 43, 3, 9, 82, 10 rangle$. A sorted version of this array would be $langle 3, 9, 10, 27, 38, 43, 82 rangle$. Next, consider an efficient, divide and conquer algorithm that can be used to {it recursively} solve the sorting problem as follows: begin{enumerate} item Divide the unsorted list into two sublists of about half the size. item Divide each of the two sublists recursively until we have list sizes of length $1$, in which case the list itself is returned (after all, a list containing only $1$ element is always considered sorted!). item Merge the two sublists back into one sorted list. end{enumerate} Suppose now that you had the following function available to you: begin{lstlisting}{} void merge(Item arr[], const int& left, const int& right, const int& pivot); end{lstlisting} that combines two {bf sorted} sub-arrays of {tt arr} (i.e., the inclusive intervals [{tt left}, {tt pivot}] and [{tt pivot}$+1$, {tt right}]) to a underline{single} {bf sorted} array. The result of this {it combined}, sorted array is stored back into {tt arr} to form a single, sorted array whose valid elements are contained in the interval [{tt left}, {tt right}]. {tt Item} refers to a type (possibly through use of a {bf typedef}) whose members are comparable (e.g., {bf int}). /* * 'a' is an array of 'Items' whose valid elements are between 'start' and 'end', * inclusively. 'mid' is the position in 'a' in which to divide the array. */ void mergesort(Item a[], const int& start, const int& end, const int& mid) { if ( start >= end ) //the array is either empty or contains a single element. return; //sorting problem already solved. Nothing to do. Example: Mergesort
  • 5. if ( start >= end ) //the array is either empty or contains a single element. return; //sorting problem already solved. Nothing to do. //sort the left portion of the array. mergesort(a, start, mid, (start + mid) / 2); //sort the right portion of the array mergesort(a, mid + 1, end, (mid + 1 + end) / 2); //combined the two sorted array portions in a single sorted array. merge(a, start, end, mid); }