2. Recursive Factorial Function
// Computes the factorial of a nonnegative integer.
// Precondition: n must be greater than or equal to 0.
// Postcondition: Returns the factorial of n; n is unchanged.
int Factorial(int n)
{
if (n == 0)
return (1);
else
return (n * Factorial(n-1));
}
void main()
{
int n; cin>>n;
Factorial(n);
}
T(n) = O(1) , if n = 0
T(n) = T(n-1)+O(1) , otherwise
O(1) time
Let factorial(n) call takes total T(n) time
So Factorial(n-1) call will take T(n-1) time
O(1) time
O(1) time
3. template<class ItemType>
bool BinarySearch(ItemType info[], ItemType item, int fromLocation,
int toLocation)
{
if (fromLocation > toLocation) // Base case 1
return false;
else
{
int midPoint;
midPoint = (fromLocation + toLocation) / 2;
if (item < info[midPoint])
return BinarySearch(info, item, fromLocation, midPoint - 1);
else if (item == info[midPoint]) // Base case 2
return true;
else
return BinarySearch(info, item, midPoint + 1, toLocation);
}
}
Binary Search: The Recursive Way
What’s its time complexity?
4. Tower of Hanoi Problem
• There is a tower of n discs stacked in increasing order of size in the first peg
• Goal: transfer the entire tower to the 3rd
peg in the fewest possible moves.
• Constraints:
• You can only move one disk at a time and
• You can never stack a larger disk onto a smaller disk.
5. Recursive Solution
• Problem: Move N discs from source peg to destination
peg using auxiliary peg as via
• Base case:
• Move disc from source peg to destination peg (N = 1)
6. Recursive Solution
• Problem: Move N discs from source peg to destination
peg using auxiliary peg as via
• General case:
• Move N-1 discs from source peg to auxiliary peg via destination
peg
• Move disc from source peg to destination peg
• Move N-1 discs from auxiliary peg to destination peg via source
peg
7. #include <stdio.h>
void hanoi(int n, char src, char dst, char aux)
{
if(n == 1)
printf("Move disc from peg %c to peg %cn", src, dst);
else
{
hanoi(n-1, src, aux, dst);
hanoi(1, src, dst, aux);
hanoi(n-1, aux, dst, src);
}
}
int main()
{
hanoi(4, 'A', 'C', 'B');
return 0;
}
Recursive Function for Solving Hanoi
What’s its time complexity?