Data Structures and Algorithms · Unit 4 · 3 hrs
Recursion
Exam-focused notes for Recursion (Data Structures and Algorithms, CSC211): what the TU syllabus asks and how it has actually been tested, with 7 solved past questions from this unit.
Recursion in short
This chapter studies recursion: how a function that calls itself can express an algorithm naturally, how it compares with an equivalent loop, and how it solves four classic problems, factorial, Fibonacci, GCD and the Tower of Hanoi, before weighing its costs and benefits.
What this unit covers
- Principle of Recursion, Comparison between Recursion and Iteration, Tail Recursion
- Factorial, Fibonacci Sequence, GCD, Tower of Hanoi(TOH)
- Applications and Efficiency of Recursion
Factorial, Fibonacci Sequence, GCD, Tower of Hanoi
2081 · 5 marks
Write a program to find GCD of two numbers using recursion. [5]
2078 · 5 marks
Write a recursive program to find nth fibonacci number. [5]
Show solved answerHide answer
Recursive Program to Find nth Fibonacci Number
Concept
The Fibonacci sequence is defined as:
- F(0) = 0
- F(1) = 1
- F(n) = F(n-1) + F(n-2) for n >= 2
This is a naturally recursive problem because the definition of F(n) directly refers to smaller instances of itself. Recursive solutions are well-suited for problems that are naturally recursive in structure.
Recurrence Relation
F(n) = F(n-1) + F(n-2)
Base cases:
F(0) = 0
F(1) = 1
Algorithm
Algorithm Fibonacci(n):
if n == 0:
return 0
else if n == 1:
return 1
else:
return Fibonacci(n-1) + Fibonacci(n-2)
C Program
#include <stdio.h>
/* Recursive function to find nth Fibonacci number */
int fibonacci(int n)
{
/* Base cases */
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
/* Recursive case: F(n) = F(n-1) + F(n-2) */
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main()
{
int n;
printf("Enter the value of n: ");
scanf("%d", &n);
printf("Fibonacci(%d) = %d\n", n, fibonacci(n));
return 0;
}
Dry Run (Trace) for n = 5
fibonacci(5)
= fibonacci(4) + fibonacci(3)
= (fibonacci(3) + fibonacci(2)) + (fibonacci(2) + fibonacci(1))
= ((fibonacci(2) + fibonacci(1)) + (fibonacci(1) + fibonacci(0)))
+ ((fibonacci(1) + fibonacci(0)) + 1)
= ((1 + 1) + (1 + 0)) + ((1 + 0) + 1)
= (2 + 1) + (1 + 1)
= 3 + 2
= 5
So, F(5) = 5 which is correct (0, 1, 1, 2, 3, 5).
Sample Output
Enter the value of n: 5
Fibonacci(5) = 5
Complexity Analysis
| Aspect | Value |
|---|---|
| Time Complexity | O(2^n) -- exponential due to overlapping subproblems |
| Space Complexity | O(n) -- recursive call stack depth |
Note: The recursive computation of Fibonacci numbers involves excessive costs due to overlapping subproblems (the same subproblems are computed multiple times). This is why it is not considered an efficient divide-and-conquer algorithm. Dynamic programming or memoization can reduce this to O(n).
2077 · 5 marks
Write a recursive program to find GCD of two numbers. [5]
2074 · 5 marks
Explain the Tower of Hanoi (TOH) with practical example. [5]
Principle of Recursion, Comparison between Recursion and Iteration, Tail Recursion
2080 · 5 marks
Explain tail recursion with example. Compare recursion with iteration. [5]
2077 · 5 marks
Write short notes on: a. Tail recursion b. Collision resolution techniques [5]
Show solved answerHide answer
Short Notes: Tail Recursion and Collision Resolution Techniques
a. Tail Recursion (2.5 marks)
Definition: Tail recursion is a special form of recursion in which the recursive call is the last operation performed in the function. There is no pending computation left to be done after the recursive call returns.
Key Characteristics:
- The recursive call appears at the tail (end) of the function body.
- Since no task is left after the recursive call, the current stack frame does not need to be preserved.
- As stated in the notes: "Tail recursion is better than non-tail recursion. As there is no task left after the recursive call, it will be easier for the compiler to organize and optimize the code."
Example:
// Non-tail recursive factorial
int fact(int n) {
if (n == 0) return 1;
return n * fact(n-1); // pending multiplication after call
}
// Tail recursive factorial
int fact_tail(int n, int acc) {
if (n == 0) return acc;
return fact_tail(n-1, n * acc); // last operation is the call itself
}
Advantages over Normal Recursion:
- Compiler can optimize tail recursion into iteration (tail call optimization), saving stack space.
- Avoids stack overflow for large inputs.
- More memory efficient since intermediate results need not be stored on the system stack.
b. Collision Resolution Techniques (2.5 marks)
Collision: A collision occurs when two distinct keys produce the same hash value and map to the same slot in a hash table.
Collision Resolution: When two items hash to the same slot, a systematic method is needed to place the second item. This process is called collision resolution.
The major techniques are:
1. Open Addressing
When a collision occurs, another location in the array is sought. It has three main methods:
i) Linear Probing:
- The colliding item is placed in the next empty slot in the array.
- Formula:
h(x) = (hash value + i) % table sizefor i = 1, 2, 3, ... - Disadvantage: Causes primary clustering (long chains of occupied slots).
Example: Insert {89, 49, 18, 58} with h(x) = x % 10
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| Value | 49 | 58 | - | - | - | - | - | - | 18 | 89 |
ii) Quadratic Probing:
- Eliminates primary clustering by using a quadratic function.
- Formula:
h(x) = (hash value + j²) % table sizefor j = 1, 2, 3, ... - On 1st collision:
(hash value + 1²) % table size - On 2nd collision:
(hash value + 2²) % table size
iii) Double Hashing:
- Uses a second hash function to determine the step size when a collision occurs.
- Reduces clustering more effectively than linear or quadratic probing.
2. Chaining
- Each slot in the hash table holds a linked list of all elements that hash to that slot.
- Colliding elements are simply appended to the list at that index.
- Easy to implement and handles multiple collisions gracefully.
3. Rehashing
- When a collision occurs, a new hash function is applied to find an alternate location.
4. Hashing Using Buckets
- Each hash table slot points to a bucket (array or block) that can hold multiple values.
Summary Table:
| Technique | Approach | Clustering |
|---|---|---|
| Linear Probing | Next empty slot | Primary clustering |
| Quadratic Probing | Quadratic step | Reduced clustering |
| Double Hashing | Second hash function | Minimal clustering |
| Chaining | Linked list at slot | No clustering |
2075 · 5 marks
Define recursive algorithm? How do you implement recursive algorithm while writing computer programs? [5]
Make Unit 4 stick
Practice CSC211 with flashcards & quizzes