Dsa L9
Dsa L9
Amit
Raj Deb
?
Ragini Rohit Sachin
https://abetterscientist.wordpress.com/
(Business organization chart)
Many more: Factorial, Fibonacci seq., Towers of Hanoi, Merge sort, Quick sort, Binary search …
LINEAR RECURSION
•A linear recursive function is a function int sumArrayRecursive(int arr[], int n) {
that makes at most one recursive call // What is the base case?
each time it is invoked (as opposed to
one that would call itself multiple times //Recursive step:
during its execution).
return arr[0] + sumArrayRecursive(???, ???);
}
int gcd(int a, int b) {
}
if (b == 0) {
int main() {
return a;
int arr[] = {1, 2, 3, 4, 5};
} else {
int n = sizeof(arr) / sizeof(arr[0]);
return gcd(b, a % b);
int sum = sumArrayRecursive(arr, n);
}
cout << "Sum of array elements: " << sum << endl;
}
return 0;
Euclidean Algorithm (Recursive) }
TAIL RECURSION: REVERSING AN ARRAY
void reverseArray(int arr[], int start, int end)void reverseArray(int arr[], int size) {
{ int start = 0;
if (start >= end) { //reached ??? int end = size - 1;
return; while (start < end) {
} swap(arr[start], arr[end]);
swap(arr[start], arr[end]); start++;
reverseArray(arr, start + 1, end - 1); end--;
} }
}
• Tail recursion occurs when a linearly recursive method makes its recursive call as its
last step.
• Such methods can be easily converted to non-recursive methods (which saves on some
resources).
WHAT ABOUT FACTORIAL?
int factorial(int n) { int tail_factorial(int n, int acc) {
if (n == 0) { if (n == 0) {
return acc;
return 1; } else {
} else { return tail_factorial(n - 1, n * acc);
return ; }
}
}
int factorial(int n) {
} return tail_factorial(n, 1);
Is it tail recursive? } What about this?
int factorial_iterative(int n) {int prod = 1; for (int i = 1; i <= n; ++i) { prod *= i;} return prod;}
BINARY RECURSION
• What is binary recursion? void towerOfHanoi(int n, char source, char
dest, char aux) {
if (n == 1) {
Algorithm BinarySum(A, i, n): cout << "Move disk 1 from " <<
Input: An array A and integers i and n source << " to " << dest << endl;
Output: The sum of n integers in A starting at index i return;
if n == 1 then }
return A[i ]; towerOfHanoi(n - 1, …, …, …);
return cout << "Move disk " << n << " from "
BinarySum(A, i, n/ 2) + BinarySum(A, i + n/ 2, n/ 2) << source << " to " << dest << endl;
towerOfHanoi(n - 1, …, …, …);
}
Let us see the recursion trace… Used heavily in merging and tree traversals…