L2 Time Complexity Recursive Function
L2 Time Complexity Recursive Function
int Factorial(int n)
{ T(n) = O(1) , if n = 0
O(1) time T(n) = T(n-1)+O(1) , otherwise
if (n == 0)
O(1) time
return (1);
else
return (n * Factorial(n-1));
} O(1) time So Factorial(n-1) call will take T(n-1) time
void main()
{
int n; cin>>n; Let factorial(n) call takes total T(n) time
Factorial(n);
Binary Search: The Recursive Way
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);
}
}
#include <stdio.h>
void hanoi(int n, char src, char dst, char aux)
{
if(n == 1)
printf("Move disc from peg %c to peg %c\n", 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;
}
What’s its time complexity?