SlideShare ist ein Scribd-Unternehmen logo
1 von 4
Downloaden Sie, um offline zu lesen
Recursion lecture in C++
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-1) + (x-2) + .. + 0, for x >= 0
* Example where x = 3, we have 3 + 2 + 1 + 0 = 6
*/
#include <iostream>
using namespace std;
//function declaration.
//finds the solution to the arthmetic series starting a x for x >= 0.
int arthmeticSeries(int x);
int main() {
int sum = arthmeticSeries(3);
cout << “The solution to x = 3 is “ << sum << endl; //prints 6.
}
Example: Arithmetic Series
int main() {
int sum = arthmeticSeries(3);
cout << “The solution to x = 3 is “ << sum << endl; //prints 6.
}
//function definition.
arthmeticSeries(int x) {
//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?
#include <iostream>
using namespace std;
int binsearch(int arr[], int start, int end, int val);
int main() {
int myArray[] = {41, 62, 77, 80, 85, 92, 104, 211, 400};
int length = 9;
int pos = binsearch(myArray, 0, length - 1, 62);
cout << pos << endl;
pos = binsearch(myArray, 0, length - 1, 97);
cout << pos << endl;
}
int binsearch(int arr[], int start, int end, int val) {
if ( start > end ) //if empty.
return -1; //not found.
Example: Binary Search
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
- 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}
Example: Mergesort
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:
void merge(Item arr[], const int& left, const int& right,
const int& pivot);
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.
//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?

02 Arrays And Memory Mapping
02 Arrays And Memory Mapping02 Arrays And Memory Mapping
02 Arrays And Memory Mapping
Qundeel
 

Was ist angesagt? (20)

Array
ArrayArray
Array
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
 
Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]
 
Arrays In C++
Arrays In C++Arrays In C++
Arrays In C++
 
02 Arrays And Memory Mapping
02 Arrays And Memory Mapping02 Arrays And Memory Mapping
02 Arrays And Memory Mapping
 
One dimensional arrays
One dimensional arraysOne dimensional arrays
One dimensional arrays
 
Data Structure
Data StructureData Structure
Data Structure
 
Array Presentation
Array PresentationArray Presentation
Array Presentation
 
Arrays
ArraysArrays
Arrays
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Arrays, continued
Arrays, continuedArrays, continued
Arrays, continued
 
Array
ArrayArray
Array
 
1 D Arrays in C++
1 D Arrays in C++1 D Arrays in C++
1 D Arrays in C++
 
Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)
 
One dimensional 2
One dimensional 2One dimensional 2
One dimensional 2
 
ARRAY
ARRAYARRAY
ARRAY
 
C++ lecture 04
C++ lecture 04C++ lecture 04
C++ lecture 04
 
Introduction to Array ppt
Introduction to Array pptIntroduction to Array ppt
Introduction to Array ppt
 
Data structure ppt
Data structure pptData structure ppt
Data structure ppt
 
Arrays Basics
Arrays BasicsArrays Basics
Arrays Basics
 

Andere mochten auch (8)

Assembly Language String Chapter
Assembly Language String Chapter Assembly Language String Chapter
Assembly Language String Chapter
 
Inline asm in c gọi hàm ngat
Inline asm in c gọi hàm ngatInline asm in c gọi hàm ngat
Inline asm in c gọi hàm ngat
 
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIATypes Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
 
Inline assembly language programs in c
Inline assembly language programs in cInline assembly language programs in c
Inline assembly language programs in c
 
4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patil4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patil
 
functions of C++
functions of C++functions of C++
functions of C++
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Tail Recursion in data structure
Tail Recursion in data structureTail Recursion in data structure
Tail Recursion in data structure
 

Ähnlich wie Recursion Lecture in C++

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
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
timourian
 

Ähnlich wie Recursion Lecture in C++ (20)

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
 
Introduction to R
Introduction to RIntroduction to R
Introduction to R
 
Statistics lab 1
Statistics lab 1Statistics lab 1
Statistics lab 1
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Computer programming 2 Lesson 13
Computer programming 2  Lesson 13Computer programming 2  Lesson 13
Computer programming 2 Lesson 13
 
Unit 6. Arrays
Unit 6. ArraysUnit 6. Arrays
Unit 6. Arrays
 
Merge radix-sort-algorithm
Merge radix-sort-algorithmMerge radix-sort-algorithm
Merge radix-sort-algorithm
 
Merge radix-sort-algorithm
Merge radix-sort-algorithmMerge radix-sort-algorithm
Merge radix-sort-algorithm
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
 
ARRAYS
ARRAYSARRAYS
ARRAYS
 
Arrays
ArraysArrays
Arrays
 
Scala collection
Scala collectionScala collection
Scala collection
 
iRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat SheetiRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat Sheet
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
 
Algorithms notes tutorials duniya
Algorithms notes   tutorials duniyaAlgorithms notes   tutorials duniya
Algorithms notes tutorials duniya
 
Arrays
ArraysArrays
Arrays
 
Module7
Module7Module7
Module7
 
Java arrays (1)
Java arrays (1)Java arrays (1)
Java arrays (1)
 
Data structure array
Data structure  arrayData structure  array
Data structure array
 
Array
ArrayArray
Array
 

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

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
kauryashika82
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
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
QucHHunhnh
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 

Kürzlich hochgeladen (20)

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
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).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
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
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.
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 

Recursion Lecture in C++

  • 1. Recursion lecture in C++ 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-1) + (x-2) + .. + 0, for x >= 0 * Example where x = 3, we have 3 + 2 + 1 + 0 = 6 */ #include <iostream> using namespace std; //function declaration. //finds the solution to the arthmetic series starting a x for x >= 0. int arthmeticSeries(int x); int main() { int sum = arthmeticSeries(3); cout << “The solution to x = 3 is “ << sum << endl; //prints 6. } Example: Arithmetic Series
  • 2. int main() { int sum = arthmeticSeries(3); cout << “The solution to x = 3 is “ << sum << endl; //prints 6. } //function definition. arthmeticSeries(int x) { //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? #include <iostream> using namespace std; int binsearch(int arr[], int start, int end, int val); int main() { int myArray[] = {41, 62, 77, 80, 85, 92, 104, 211, 400}; int length = 9; int pos = binsearch(myArray, 0, length - 1, 62); cout << pos << endl; pos = binsearch(myArray, 0, length - 1, 97); cout << pos << endl; } int binsearch(int arr[], int start, int end, int val) { if ( start > end ) //if empty. return -1; //not found. Example: Binary Search
  • 3. 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 - 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} Example: Mergesort
  • 4. 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: void merge(Item arr[], const int& left, const int& right, const int& pivot); 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. //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); }