Loading...

DESIGN & ANALYSIS OF ALGORITHMS  

LEARNING OUTCOME 2

Recursion

Recursion is a programming technique where a function calls itself directly or indirectly. This creates a loop-like structure, but instead of using explicit iteration control, recursion relies on function calls to repeat the process.

Recursion vs. Iteration

Feature Recursion Iteration
Control flow Function calls Looping constructs (e.g., for, while)
Stack usage Function calls create a stack frame for each recursive call. Iteration uses a loop counter or condition.
Clarity Can sometimes be more intuitive for certain problems. Often more straightforward for simple tasks.
Efficiency Can be less efficient due to function call overhead. Can be more efficient for certain problems.
Tail-call optimization Some compilers can optimize tail-recursive functions. Not applicable to iteration.
Memory usage Can consume more memory due to the stack frames created by function calls. Generally more memory-efficient.
Complexity Can be more complex to understand and debug. Often easier to understand and debug.
Problem domains Well-suited for problems that can be broken down into smaller, similar subproblems. More suitable for problems that involve a fixed number of repetitions.

Types of Recursion

Critique of Recursion

Laws of Recursion

C++ RECURSIVE ALGORITHMS

FACTORIAL:

int factorial(int n) {
			if (n == 0) {
				return 1; // Base case
			} else {
				return n * factorial(n - 1); // Recursive case
			}
		}

TOWERS OF HANOI:

void towersOfHanoi(int n, char source, char destination, char auxiliary) {
			if (n == 1) {
				cout << "Move disk 1 from " << source << " to " << destination << endl;
				return;
			}
			towersOfHanoi(n - 1, source, auxiliary, destination);
			cout << "Move disk " << n << " from " << source << " to " << destination << endl;
			towersOfHanoi(n - 1, auxiliary, destination, source);
		}

Binary search:

int binarySearch(int arr[], int left, int right, int x) {
			if (right >= left) {
				int mid = left + (right - left) / 2;
				if (arr[mid] == x)
					return mid;
				if (arr[mid] > x)
					return binarySearch(arr, left, mid - 1, x);
				return binarySearch(arr, mid + 1, right, x);
			}
			return -1;
		}

Fibonacci sequence:

int fibonacci(int n) {
			if (n <= 1) {
				return n;
			} else {
				return fibonacci(n - 1) + fibonacci(n - 2);
			}
		}

End of Outcome Quiz

1 of 20

    Quiz Score

    Percentage: 0%

    Answered Questions: 0

    Correct Answers: 0

    Faults: