4 Recursion

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.

Recursion: notes

Principle of Recursion, Comparison between Recursion and Iteration, Tail Recursion

Recursion is the technique in which a function solves a problem by calling itself on a smaller instance of the same problem, until the instances become small enough to be solved directly. Every correct recursive function needs two parts: a base case that stops the recursion without a further call, and a recursive case that reduces the original problem to one or more smaller sub-problems of exactly the same shape, then combines their solutions. Recursion and iteration both repeat work, but they do so differently:

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]

The GCD (Greatest Common Divisor) of two numbers is based on the Euclidean Algorithm: - If b == 0, then GCD(a, b) = a - Otherwise, GCD(a, b) = GCD(b, a % b) This is a naturally recursive problem, and Recursion helps solve problems that are naturally recursive in structure. --- --- Input: num1 = 4...

Open this answer on its own page →

2078 · 5 marks

Write a recursive program to find nth fibonacci number. [5]

Show solved 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

AspectValue
Time ComplexityO(2^n) -- exponential due to overlapping subproblems
Space ComplexityO(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).

Open this answer on its own page →

2077 · 5 marks

Write a recursive program to find GCD of two numbers. [5]

The GCD (Greatest Common Divisor) of two numbers is based on Euclid's Algorithm: - If b == 0, then GCD(a, b) = a - Otherwise, GCD(a, b) = GCD(b, a % b) This is a naturally recursive problem where each call reduces the problem size until the base case is reached. --- --- --- Input: a = 48, b = 18 ...

Open this answer on its own page →

2074 · 5 marks

Explain the Tower of Hanoi (TOH) with practical example. [5]

Tower of Hanoi is a classic mathematical puzzle that is naturally recursive in nature. It involves moving a set of disks from one peg to another following specific rules. TOH is one of the best examples of a problem that is naturally recursive and is a key advantage of using recursion. --- 1. The...

Open this answer on its own page →

Principle of Recursion, Comparison between Recursion and Iteration, Tail Recursion

2080 · 5 marks

Explain tail recursion with example. Compare recursion with iteration. [5]

--- Tail recursion is a special form of recursion where the recursive call is the last operation performed in the function. That is, after the recursive call returns, there is nothing left to do in the calling function. Because of this property, the compiler or interpreter can optimize tail-recur...

Open this answer on its own page →

2077 · 5 marks

Write short notes on: a. Tail recursion b. Collision resolution techniques [5]

Show solved 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 size for i = 1, 2, 3, ...
  • Disadvantage: Causes primary clustering (long chains of occupied slots).

Example: Insert {89, 49, 18, 58} with h(x) = x % 10

Index0123456789
Value4958------1889

ii) Quadratic Probing:

  • Eliminates primary clustering by using a quadratic function.
  • Formula: h(x) = (hash value + j²) % table size for 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:

TechniqueApproachClustering
Linear ProbingNext empty slotPrimary clustering
Quadratic ProbingQuadratic stepReduced clustering
Double HashingSecond hash functionMinimal clustering
ChainingLinked list at slotNo clustering
Open this answer on its own page →

2075 · 5 marks

Define recursive algorithm? How do you implement recursive algorithm while writing computer programs? [5]

An algorithm is a process or set of rules to be followed in calculations or other problem-solving operations by a computer. A recursive algorithm is an algorithm that solves a problem by defining the problem in terms of itself. The underlying mechanism is recursion -- the process in which a funct...

Open this answer on its own page →