Algorithms Analysis and Design Lec 4,5
Algorithms Analysis and Design Lec 4,5
We solve this question using simple recursion. To get the three disks over to the final tower you
need to :
Take the disk number 1 and 2 to tower B.
Move disk number 3 to tower C.
Take disk number 1 and 2 from B to C.
Of course, you can’t do it like this because of the constraints. However, we can use this to create
a function that does it recursively.
public static void hanoi(int n, char from, char to, char temp)
{
if (n == 1)
System.out.println(from + " --------> " + to);
else
{
hanoi(n - 1, from, temp, to);
System.out.println(from + " --------> " + to);
hanoi(n - 1, temp, to, from);
}
}
The recurrence relation for the running time of the method hanoi is:
T(n) = a if n = 1
T(n) = 2T(n - 1) + b if n > 1
Expandions:
T(n) = 2[2T(n – 2) + b] + b = 22 T(n – 2) + 3b by substituting T(n – 1)
= 22 [2T(n – 3) + b] + 3b = 23 T(n – 3) + 7b by substituting T(n-2)
= 23 [2T(n – 4) + b] + 7b = 24 T(n – 4) + 15b by substituting T(n – 3)
=2k T(n – k) + (2k -1)b
The base case is reached when n – k = 1 → k = n – 1, we then have:
T(n)= (2n-1)a+(2n-1-1)b=(2n-1)(a+b)-b
Therefore, The method hanoi is O(2n)
Master Theorem (Master Method)
The master method provides an estimate of the growth rate of the solution for recurrences of the
form:
Example1: Find the big-Oh running time of the following recurrence. Use the Master
Theorem:
Example3: Find the big-Oh running time of the following recurrence. Use the Master Theorem:
T(1) = 1
T(n) = 4T(n / 2) + kn3 + h where k ≥ 1 and h 1
Solution: a = 4, b = 2, c = 3 → a < bc → Case 3
Hence T(n) is O(n3)
Example4: Find the big-Oh running time of the following recurrence. Use the Master Theorem:
T(0) = 1 n=0
T(n) = 5 + T(n – 1) n>0
a=1, k=5 , c=0, b=1
Not that b is not ≥1 so we can’t use the Master Theorem
Example5: Analysis Of Recursive Binary Search Use the Master
public int binarySearch (int target, int[] array,
int low, int high) {
if (low > high)
return -1;
else {
int middle = (low + high)/2;
if (array[middle] == target)
return middle;
else if(array[middle] < target)
return binarySearch(target, array, middle + 1, high);
else
return binarySearch(target, array, low, middle - 1);
}
}
Binary search Find an element in a sorted array:
1. Divide: Check middle element.
2. Conquer: Recursively search 1subarray.
3. Combine: Trivial.
Example 4 : Find 9 in array 3 5 7 8 9 12 15
Steps
➢ 3 5 7 8 9 12 15
➢ 3 5 7 8 9 12 15
➢ 3 5 7 8 9 12 15
➢ 3 5 7 8 9 12 15
➢ 3 5 7 8 9 12 15
The recurrence relation for the running time of the method is:
T(1) = 1 if n = 1 (one element array)
T(n) = T(n / 2) + 4 if n > 1
Solution: a = 1, b = 2, c = 0 → a = bc → Case 2 Hence 𝑇(𝑛) ∈ 𝑂(𝑛c log 𝑛) = 𝑂(log 𝑛)
Analysis Of Recursive Merge Sort
Divide:
• [38, 27, 43, 10] is divided into [38, 27 ] and [43, 10] .
• Merge [27, 38] and [10,43] to get the final sorted list [10, 27, 38, 43]