Lecture 10: Algorithms and Data Structures

What You Will Learn Today

Recursion

Advantages Disadvantages
  • Can be shorter and easier to design and code
  • Can better model how we think of the problem
  • More method calls uses more stack space and memory
  • May run slower (usually not much)

Recursive Problem-Solving Steps

  1. Consider various ways for simplifying inputs.
  2. Combine solutions with simpler inputs into solution to the original problem.
  3. Find special-case solutions to the simplest inputs.
  4. Implement by combining simple cases and reduction steps.
  5. Test with different inputs including invalid ones

Factorial

  Iterative Recursive
Method
Code
int factorial (int n)
{
   int fact = 1;
   for (int i = 2; i <= n; i++)
      fact *= i;
   return fact;
}
int factorial (int n)
{
   if (n <= 1) // not n == 1
      return 1;
   else
      return n * factorial(n - 1);
}
Example
n=3
i fact
2 2 * 1 = 2
3 3 * 2 = 6
  factorial(3)
= 3 * factorial(2)
= 3 * 2 * factorial(1)
= 3 * 2 * 1
= 3 * 2
= 6

Greatest Common Divisor

In mathematics, the greatest common divisor is the largest number which can divide two numbers exactly (with no remainder/modulus)

int gcd (int a, int b)
{
   if (b < a) return gcd(b, a);
   if (b % a == 0) return a;
   else return gcd(b, b % a);
}

Example: gcd (12, 20) = gcd (12, 20 % 12) = gcd (12, 8) = gcd (8, 12) = gcd (8, 12 % 8) = gcd (8, 4) = gcd (4, 8) = 4. Check: 12/4=3, 20/4=5
gcd (60, 105) = ?
gcd (396, 144) = ?

Towers of Hanoi

Traversing a Maze

A Few Other Applications of Recursion

Collections

Abstract Data Types

Dynamic Data Structures

Linked Lists

Stacks

Queues

Sorting Algorithms

Searching Algorithms

To Do After Class