Algorithm Design and Analysis Guide
Algorithm Design and Analysis Guide
OR
Representation of Algorithm
1. Give a description in your own language, e.g. English, Spanish, …
2. Pseudo code
3. Graphical
Usually:
45
19 (x
405
45 (+
855
45 19 19
22 38
11 76 76
5 152 152
2 304
1 608 608 (+
855
This algorithm can be used for multiplying any two positive integers, we say
that (45, 19) is an instance of this problem. Most problems have infinite
collection of instances.
It’s ok to define the domain (i.e. the set of instances) to be considered, and
the algorithm should work for all instances in that domain.
Although the above algorithm will not work if the first operand is negative,
this does not invalidate the algorithm since (-45, 19) is not an instance of
the problem being considered.
Design and Analysis of Algorithm 9
Silicon Institute of Technology Order
Usually we use the frequency count to compare algorithms.
Consider the following 3 programs:
No matter which machine we use to run these programs, we know that the execution time of
(b) is n times the execution time of (a).
Time Complexity :
Time complexity deals with finding out how the computational time of an algorithm changes
with the change in size of the input
Space Complexity:
Space complexity deals with finding out how much (extra)space would be required by the
algorithm with change in the input size
Not Much importance is given to space complexity:
• Less Cost/ Can be easily increased
• Incase of Embedded System and Mobile applications or memory constraint applications
this is emphasized
Static Dynamic
Objective Measures Objective Measures
(Program Length) (Time and Space)
Algorithm Analysis
T(n) =3
T(n) =2n+3
T(n) =(c2+c3)n+c1+c2+c4
Design and Analysis of Algorithm
Silicon Institute of Technology Analysis as dominant operation
for i ← 1 to n do
for j ← 1 to n do
x←x+y
end
end T(n) =c1 n2 + c2 n + c3
for i ← 1 to n do Can be ignored for larger value of n
x←x+y
end
x←x+y
Thank You
Silicon Institute of Technology
Asymptotic Analysis
T1(n) = n2 + n
Lets assume each algorithm takes 1 sec to execute for n=100
How long will it take for n=1000?
T2(n) = n2
Time2 = 1 x = 100
Solution:
As per definition of Big-Oh notation t(n) ≤ c g(n)
and we can see for all value of c ≥ 4 this relation holds good
So t(n) is in O(g) or the algorithm is in O(n3)
Silicon Institute of Technology Big-Oh Notation (O)
Let t(n) = 3n3+ 2n2 + 3 for an algorithm. Let g(n) = n3. Prove that t(n) of
this algorithm is in O(g(n))
So we need to show
3n3+ 2n2 + 3 ≤ cn3 for some positive integer c
t(n) = 3n3+ 2n2 + 3
≤ 3n3+ 2n3 + 3n3 (as 2n3 > 2n2 and 3n3> 3n for any positive
integer n)
≤ 8n3
So t(n) ≤ 8n3 → t(n) is in O(n3)
Silicon Institute of Technology Big-Oh Notation (O)
Let t(n) = (2n3+ 13 log n)/7n2 for an algorithm. Prove that t(n) of this
algorithm is in O(n)
It can be observed that log n < n always hold good
So 13 log n < 13n and 13n < 13 n3
so t(n) ≤ (2n3 + 13 n3) / 7n2
≤ 15 n3 / 7n2
≤(15/7) n
≤3n
So t(n) is in O(n)
Silicon Institute of Technology Properties of Big-Oh notation
• For big-Oh analysis only the dominating summands maters. For
example O(4n4+7n2+7) = O(n4), all term other than highest degree are
ignored.
• In addition, in the big-Oh notation, the constant factors are not
significant. For example O(3n2) = O(n2)
• Big-Oh can be used to express tight bounds.
• A bound is called tight bound or least upper bound if the difference
between the bound and the actual function is a constant.
• For example n2 can not be expressed as O(n3), it can only be
expressed in O(n2), as it is the best fit.
Silicon Institute of Technology Big-Omega Notation(Ω)
Definition: Let t and g be the two functions that
map a set of natural numbers to a set of positive Ω 𝑔 𝑛 = {f(n): there exist positive
real number N → 𝑅≥0 constant c and n0 such that 0 ≤ cg(n) ≤ f(n)
for all n > n0}
Let Ω(g) be the set of all functions that have a
similar growth rate.
The relation t(n) = Ω(g(n)) holds good if and only if
there exist two positive constants c and n0 such
that
t(n) ≥ c x g(n) ∀ n > n0
The function t(n) is said to be in Ω(g(n)) means
t(n) ∈ Ω 𝑔 𝑛 But represented as t(n) = Ω(g(n))
The Lower Bound of an algorithm is given by Big-Omega.
Silicon Institute of Technology Big-Omega Notation(Ω)
Let t(n) = n4+ 3n3 + 2n +1 for an algorithm. Let g(n) = n4 + 1. Prove that
t(n) of this algorithm is in Ω(g(n))
So we need to show
n4+ 3n3 + 2n +1 ≥ c (n4 + 1) for some positive integer c
for all value of c > 0 this relation holds good
so t(n) is in Ω(g(n))
Silicon Institute of Technology Big-Omega Notation(Ω)
If the relation t(n) = 6n2 + 7n +8 holds, Prove that t(n) of not in Ω(n3)
2. For any polynomial of the order of K, one can show that t(n) is in 𝜃(nk)
Silicon Institute of Technology examples of Big-Theta Notation
Consider an algorithm that is assumed to run in time O(n2) and that takes
only five seconds to compute result of an instance of size 30. how long
will the algorithm take to compute the results if the instance size is
increased to 50?
As t(n) is in O(n2)
t(n) ≤ c x (n2)
cn2 steps = 5 sec
c (30)2 = 5
c = 5/ 900
Now for the second case t = c x (50)2 = 2500 x 5/900 = 125/9 = 13.88 secs
Silicon Institute of Technology examples of Big-Theta Notation
Supposed that an algorithm takes eight seconds to run on an input size n
=12. Estimate the instances that can be proposed in 56 secs. Assume that
the algorithm complexity is 𝜃(n)
As t(n) is in 𝜃(n)
12c = 8 sec
c = 8/12 = 2/3
Now need to calculate n for t = 56
c n= 56
n = 56 x 3/2
n = 84
Hence, the maximum input that is possible is 84
Silicon Institute of Technology Little-oh Notation
Little –Oh notation is similar to Big-Oh but it represents a loose bound
Definition :
The relation t(n) = o(g(n)) holds good, if there exist two positive
constants c and n0 such that
𝑡(𝑛)
if lim =0 then t(n) = o(g(n)) holds good
𝑛→∞ 𝑔(𝑛)
Silicon Institute of Technology Example for little-Oh
Let t(n) = 7n + 6. show that t(n) is in o(n2)
𝑡(𝑛)
As we know, if t(n) = o(g(n)) holds good when lim =0
𝑛→∞ 𝑔(𝑛)
7𝑛+6 7 2
=> lim = lim + =0
𝑛→∞ n2 𝑛→∞ n 𝑛 2
So if f(n) and g(n) grows at the same growth. Then one can write that
t(n) ~ g(n)
Silicon Institute of Technology Asymptotic Rules
Reflexive Rule
t(n) = O(g(n))
t(n) = Ω(g(n))
=> t(n) = 𝜃(g(n))
Transitivity Rule
If t(n) = O(g(n)) and g(n) = O(h(n))
Then t(n) = 𝑂(h(n))
Law of Composition
If O(O(t(n))) = O(t(n))
Silicon Institute of Technology Law of Addition
Segment 1: complexity -> n
Segment 2: complexity -> log n Total Complexity = n + log n + n2
Segment 3: complexity -> n2
Thank You
Silicon Institute of Technology
Recurrence Relation
tn = tn-1 + tn-2
In general term recurrence equations are represented in the
Linear Non Linear
following form
Recurrence Relation Recurrence Relation
a0tn + a1tn-1 + a2tn-2 .... + aktn-k = f(n)
Non Linear Recurrence Equation
If in a recurrence equation the final term tn is a non linear combination of its previous terms
𝑛 𝑛
𝑇 𝑛 = 𝑎𝑇 𝑏
+ 𝑓(𝑛) where a is the number of sub problem of size 𝑏 each and f(n) is the cost of work
done as non recursive call. Binary
Silicon Institute of Technology Order of Recurrence Equation
The number of preceding terms are being used for computing the
present term is known as order of the recurrence equation
Homogeneous Test: Replace all t terms with zero and see the equation
Silicon Institute of Technology Constant vs Variable Co-efficient
a0tn + a1tn-1 + a2tn-2 .... + aktn-k = f(n)
tn = n x tn-2
As the first step guess the solution by substituting the different values of n to
generate the sequence from the recurrence equation
If we assume its true for n and then proof for n+1 then method of
induction can be established
Silicon Institute of Technology Substitution Method: Example
Verify
Let n=0 : t0 = 2 x 0 + 1 = 1
Let n=1 : t1 = 2 x 1 + 1 = 3
Let n=2 : t3 = 2 x 2 + 1 = 5
n
n
n
n/2 n/2
n/2 n/2
n 0 1 n n
2 4 n/4 n
n/4 n/4 n/4 n/4
….. ….. ….. ….
k 2k n/2k n
….. ….. ….. …..
1 1 1 1 log2 n 2log n = n 1 n
Total Work Done (1+log n) x n
Total Work Done = n + n log n which is in 𝜽(n log n) => Asymptotic bound is 𝜽(n log n)
Silicon Institute of Technology Another Example
Consider the following Recurrence
Determine the final asymptotic
complexity of the tree for a=1 and a=n
1 0 1 1 1 n 0 1 n n
2 1 1 1 2 1 n–2 n–2
n-2
1
...
…… …… …… ……
...
…… …… …… …..
1 n-1 1 1 1 1 n-1 1 1 1
Level = log n
the problem size is decreasing
𝑛 𝑛
𝑛, , , ….. 1 in log2n steps
2 4
Amount of work done in the last Level
= 8 log n x T(1) = n log 8 x 1 = n3
Work done at other levels : n - 4n - 16 n …. => 4in
𝑙𝑜𝑔𝑛−1 𝑖
σ
Total Work Done = 𝑖=𝑜 4 n + n3
Silicon Institute of Technology
𝑙𝑜𝑔𝑛−1 𝑖 𝑙𝑜𝑔𝑛−1 𝑖
Total Work Done = σ𝑖=𝑜 4 n + n3 = n σ𝑖=𝑜 4 + n3
=n + n3
=n + n3
=n + n3
= + n3 =
Silicon Institute of Technology Master Theorem
Simplified Master Theorem
Theorem
Let the Time Complexity function T(n) be a positive and eventually a
non-decreasing function of the following form
Case 2: When a = bk
T(n) ∈ 𝜃(𝑛𝑘log n)
Solution
𝑙𝑜𝑔𝑏𝑎 ∈
1. If f(n) = O 𝑛 /𝑛 for some constant ∈ > 0, then T(n) = 𝜃(𝑛𝑙𝑜𝑔𝑏𝑎 )
2. If f(n) = 𝜃 𝑛𝑙𝑜𝑔𝑏𝑎 then T(n) = 𝜃(𝑛𝑙𝑜𝑔𝑏𝑎 𝑙𝑜𝑔 𝑛)
𝑙𝑜𝑔𝑏𝑎 ∈
3. If f(n) = Ω 𝑛 . 𝑛 for ∈ > 0 and af(𝑛/𝑏)≤ 𝜕𝑓 𝑛 𝑓𝑜𝑟 𝜕<1, then T(n) = 𝜃(𝑓(𝑛))
Silicon Institute of Technology Example
Condition: a ≥ 1 b > 1 n0 ≥ 1 d > 0 and f(n) should be positive for n > n 0
Solution
∈
1. If f(n) = O 𝑛𝑙𝑜𝑔𝑏𝑎 /𝑛 for some constant ∈ > 0, then T(n) = 𝜃(𝑛𝑙𝑜𝑔𝑏𝑎 )
2. If f(n) = 𝜃 𝑛𝑙𝑜𝑔𝑏𝑎 then T(n) = 𝜃(𝑛𝑙𝑜𝑔𝑏𝑎 𝑙𝑜𝑔 𝑛)
∈
3. If f(n) = Ω 𝑛𝑙𝑜𝑔𝑏𝑎 . 𝑛 for ∈ > 0 and af(𝑛/𝑏)≤ 𝜕𝑓 𝑛 𝑓𝑜𝑟 𝜕<1, then T(n) = 𝜃(𝑓(𝑛))
Recurrence Equation
T(n) = 8 T(n/2) + n2
Recurrence Equation
T(n) = 2 T(n/2) + n
a = 2, b=2 and f(n) = n
𝑛𝑙𝑜𝑔𝑏𝑎 = 𝑛𝑙𝑜𝑔22 = 𝑛
n = 𝜃(𝑛𝑙𝑜𝑔𝑏𝑎 ) = 𝜃(𝑛)
Recurrence Equation
T(n) = T(2n/3) + 1
a = 1, b=3/2 and f(n) = 1
𝑛𝑙𝑜𝑔𝑏𝑎 = 𝑛𝑙𝑜𝑔3/21 = 𝑛0 = 1
n = 𝜃(𝑛𝑙𝑜𝑔𝑏𝑎 ) = 𝜃(1)
Here = = = =
1 ∈
Although we know is less then n for any value of ∈ but they are not polynomially
𝑙𝑜𝑔𝑛
comparable
Silicon Institute of Technology
Thank You
Silicon Institute of Technology
2
Silicon Institute of Technology Divide-and-Conquer Technique (cont.)
a problem of size n
subproblem 1 subproblem 2
of size n/2 of size n/2
a solution to a solution to
subproblem 1 subproblem 2
a solution to
the original problem
3
Silicon Institute of Technology Divide-and-Conquer Examples
4
Silicon Institute of Technology General Divide-and-Conquer Recurrence
5
Silicon Institute of Technology Merits and Demerits
Merit
• It is the most applied design technique
• It leads to effective recursive algorithm
• Recursive algorithms are compact and efficient compared to iterative
algorithm
Demerit
• They are not very effective when the division of the problem are
unbalanced
Silicon Institute of Technology Mergesort Example
8 3 2 9 7 1 5 4
8 3 2 9 7 1 5 4
8 3 2 9 71 5 4
8 3 2 9 7 1 5 4
3 8 2 9 1 7 4 5
2 3 8 9 1 4 5 7
1 2 3 4 5 7 8 9
7
Silicon Institute of Technology Mergesort
• Split array A[0..n-1] in two about equal halves and make copies of
each half in arrays B and C
• Sort arrays B and C recursively
• Merge sorted arrays B and C into array A as follows:
• Repeat the following until no elements remain in one of the arrays:
• compare the first elements in the remaining unprocessed portions of
the arrays
• copy the smaller of the two into A, while incrementing the index
indicating the unprocessed portion of that array
• Once all elements in one of the arrays are processed, copy the remaining
unprocessed elements from the other array into A.
8
Silicon Institute of Technology Pseudocode of Mergesort
10
Silicon Institute of Technology Merge Sort Time Analysis
Merge(left[0…p-1], right[0…q-1], A[0…n-1])
{
i <- 0; j <- 0; k <- 0; C1
If (i=p)
copy right[j… q-1] to A[k… n-1]
else
copy right[i… p-1] to A[k… n-1]
}
Silicon Institute of Technology Merge Sort Time Analysis
MergeSort(A)
{
n = length(A) Time complexity
if (n < 2) return;
mid = n/2 Constant Time: C3
left <- array of size (mid)
right<- array of size (mid)
for I =0 to mid-1
left[i] = a[i]
Appling Master Theorem
for I =mid to n-1 n . C4
left[i-mid] = a[i] T(n) = 𝜃 (𝑛 log 𝑛)
MergeSort(left)
T( n/2) each total 2T(n/2)
MergeSort(right)
Merge(left, right, A) C1 + n. C2
}
Silicon Institute of Technology Space Complexity
MergeSort(A)
{
n = length(A)
if (n < 2) return;
mid = n/2
left <- array of size (mid)
right<- array of size (mid)
for I =0 to mid-1
left[i] = a[i]
for I =mid to n-1
left[i-mid] = a[i]
MergeSort(left)
MergeSort(right)
Merge(left, right, A)
}
Silicon Institute of Technology Space Complexity:
Additional Memory for Left and Right
L1 => 2 x 4 = 8
L2 => 4 x 2 = 8
L3 => 8 x 1 = 8
Log n layers n element each
QUICK SORT
Silicon Institute of Technology QuickSort Design
• Follows the divide-and-conquer paradigm.
• Divide: Partition (separate) the array A[p..r] into two (possibly empty)
subarrays A[p..q–1] and A[q+1..r].
• Each element in A[p..q–1] < A[q].
• A[q] < each element in A[q+1..r].
• Index q is computed as part of the partitioning procedure.
• Conquer: Sort the two subarrays by recursive calls to quicksort.
next iteration: 2 5 8 3 9 4 1 7 10 6
i j Partition(A, p, r)
x := A[r]; I:= p – 1;
next iteration: 2 5 8 3 9 4 1 7 10 6 for j := p to r – 1 do
i j if A[j] x then
i := i + 1;
next iteration: 2 5 8 3 9 4 1 7 10 6 A[i] A[j]
i j A[i + 1] A[r];
return i + 1
next iteration: 2 5 3 8 9 4 1 7 10 6
i j
Silicon Institute of Technology Example (Continued)
next iteration: 2 5 3 8 9 4 1 7 10 6
i j
next iteration: 2 5 3 8 9 4 1 7 10 6
i j
next iteration: 2 5 3 4 9 8 1 7 10 6 Partition(A, p, r)
i j x:= A[r], i := p – 1;
next iteration: 2 5 3 4 1 8 9 7 10 6 for j := p to r – 1 do
i j if A[j] x then
next iteration: 2 5 3 4 1 8 9 7 10 6 i := i + 1;
i j A[i] A[j]
next iteration: 2 5 3 4 1 8 9 7 10 6 A[i + 1] A[r];
i j return i + 1
after final swap: 2 5 3 4 1 6 9 7 10 8
i j
Silicon Institute of Technology Partitioning
• Select the last element A[r] in the subarray A[p..r] as the pivot – the element
around which to partition.
• As the procedure executes, the array is partitioned into four (possibly empty)
regions.
1. A[p..i ] — All entries in this region are < pivot.
2. A[i+1..j – 1] — All entries in this region are > pivot.
3. A[r] = pivot.
4. A[j..r – 1] — Not known how they compare to pivot.
• The above hold before each iteration of the for loop, and constitute a loop
invariant. (4 is not part of the loopi.)
p i j r
x
x >x
Silicon Institute of Technology Correctness of Partition
Use loop invariant.
Initialization:
• Before first iteration
• A[p..i] and A[i+1..j – 1] are empty – Conds. 1 and 2 are satisfied
(trivially).
• r is the index of the pivot
Partition(A, p, r)
• Cond. 3 is satisfied.
x:= A[r], i:= p – 1;
Maintenance: for j := p to r – 1 do
• Case 1: A[j] > x if A[j] x then
i := i + 1;
• Increment j only.
A[i] A[j]
• Loop Invariant is maintained. A[i + 1] A[r];
return i + 1
Silicon Institute of Technology Correctness of Partition
Case 1:
p i j r
>x x
x >x
p i j r
x
x >x
Silicon Institute of Technology Correctness of Partition
p i j r
x x
x >x
p i j r
x
x >x
Silicon Institute of Technology Correctness of Partition
• Termination:
• When the loop terminates, j = r, so all elements in A are partitioned into one
of the three cases:
• A[p..i] pivot
• A[i+1..j – 1] > pivot
• A[r] = pivot
• The last two lines swap A[i+1] and A[r].
• Pivot moves from the end of the array to between the two subarrays.
• Thus, procedure partition correctly performs the divide step.
Silicon Institute of Technology Quicksort Overview
To sort a[left...right]:
1. if left < right:
Partition a[left...right] such that:
all a[left...p-1] are less than a[p], and
all a[p+1...right] are >= a[p]
Quicksort a[left...p-1]
Quicksort a[p+1...right]
2. Terminate
Silicon Institute of Technology Partitioning in Quicksort
• A key step in the Quicksort algorithm is partitioning the array
• We choose some (any) number p in the array to use as a pivot
• We partition the array into three parts:
To partition a[left...right]:
1. Set pivot = a[left], l = left + 1, r = right;
2. while l < r, do
2.1. while l < right & a[l] < pivot , set l = l + 1
2.2. while r > left & a[r] >= pivot , set r = r - 1
2.3. if l < r, swap a[l] and a[r]
3. Set a[left] = a[r], a[r] = pivot
4. Terminate
Silicon Institute of Technology Example of partitioning
• choose pivot: 436924312189356
• search: 436924312189356
• swap: 433924312189656
• search: 433924312189656
• swap: 433124312989656
• search: 433124312989656
• swap: 433122314989656
• search: 433122314989656
• swap with pivot: 133122344989656
Silicon Institute of Technology Partition Implementation (C)
Partition(A, p, r)
x, i := A[r], p – 1;
for j := p to r – 1 do
if A[j] x then
i := i + 1;
A[i] A[j]
A[i + 1] A[r];
return i + 1
Silicon Institute of Technology Analysis of quicksort—best case
• Suppose each partition operation divides the array almost
exactly in half
• Then the depth of the recursion in log2n
• Because that’s how many times we can halve n
• We note that
• Each partition is linear over its subarray
• All the partitions at one level cover the complete array
Silicon Institute of Technology Best Case Analysis
• We cut the array size in half each time
• In the worst case, partitioning always divides the size n array into these
three parts:
• A length one part, containing the pivot itself
• A length zero part, and
• A length n-1 part, containing everything else
• We don’t recur on the zero-length part
• Recurring on the length n-1 part requires (in the worst case) recurring
to depth n-1
Silicon Institute of Technology
Worst case partitioning
Silicon Institute of Technology Worst case for quicksort
• In the worst case, recursion may be n levels deep (for an array of size n)
• But the partitioning work done at each level is still n
Note these last two rules are not really language specific, but rather
how the language is typically used.
Silicon Institute of Technology
Thank You
Silicon Institute of Technology
n-2
n-1
n
Balanced Balanced Not balanced
Silicon Institute of Technology Left-justified binary trees
• A balanced binary tree of depth n is left-justified if:
• it has 2n nodes at depth n (the tree is “full”), or
• it has 2k nodes at depth k, for all k < n, and all the leaves at depth n
are as far left as possible
8 3 8 12 8 14
Red node has Red node has Red node does not
heap property heap property have heap property
• All leaf nodes automatically have the heap property
• A binary tree is a heap if all nodes in it have the heap property
Silicon Institute of Technology siftUp
• Given a node that does not have the heap property, you can give it the heap
property by exchanging its value with the value of the larger child
12 14
8 14 8 12
Blue node does not Blue node has
have heap property heap property
4 5 6 7
19 22 14 15
8 9 10 11 12 13
18 14 21 3 9 11
25 22 17 19 22 14 15 18 14 21 3 9 11
0 1 2 3 4 5 6 7 8 9 10 11 12 13
Silicon Institute of Technology Parent, Left and Right in array
25 22 17 19 22 14 15 18 14 21 3 9 11 PARENT(i)
{
return(i/2)
0 1 2 3 4 5 6 7 8 9 10 11 12 13 }
LEFT(i)
{
Parent of i => 𝑖/2 MAX-Heap return(2i)
A(PARENT(i)) >= A(i) }
Left of i => 2 i
MIN-Heap RIGHT(i)
Right of i => 2 i +1 A(PARENT(i)) <= A(i) {
return(2i+1)
}
Silicon Institute of Technology Building up to heap sort
Alg: MAX-HEAPIFY(A, i)
• In order to maintain the Max Heap
1. l ← LEFT(i)
property we call procedure 2. r ← RIGHT(i)
MAX-HEAPIFY( A, i) 3. if l ≤ Heap-Size(A) and A[l] > A[i]
4. then largest ←l
• This function ensures the sub-tree 5. else largest ←i
6. if r ≤ Heap-Size(A) and A[r] > A[largest]
rooted at index i obeys the MAX-
7. then largest ←r
HEAP property 8. if largest i
9. then exchange A[i] ↔ A[largest]
10. MAX-HEAPIFY(A, largest)
Silicon Institute of Technology
MAX-HEAPIFY( A, 2)
16 16
i 4 10 14 10
i
14 7 9 3 4 7 9 3
2 8 1 2 8 1
16
14 10
8 7 9 3
2 i 4 1
Silicon Institute of Technology Building a heap from an array - I
• We have an existing Array … A[1…n] where n is [Link], we want to
convert it into MAX-HEAP
• By default leaf nodes are MAX-HEAP
• The elements A[(n/2)+1] to A[n] are the leaf nodes of the tree all other
nodes from A[1] to A[n/2] are non-leaf nodes.
• We can call the MAX-HEAPIFY function bottom up manner for all non leaf
nodes 4
Alg: BUILD-MAX-HEAP(A)
1 3
1. Heap-Size(A) = length[A]
2. for i ← length[A] /2 downto 1 2 16 9 10
3. do MAX-HEAPIFY(A, i) 14 8 7
Silicon Institute of Technology Building a heap from an array - II
Need to built a heap from a given array
4 1 3 2 16 9 10 14 8 7
0 1 2 3 4 5 6 7 8 9 10
4 4
1 3 1 3
2 i 16 9 10 i 2 16 9 10
14 8 7 14 8 7
Silicon Institute of Technology Building a heap from an array - III
4 4
1 i 3 i 1 10
14 16 9 10 14 16 9 3
2 8 7 2 8 7
4 16
16 10 14 10
14 7 9 3 8 7 9 3
2 8 1 2 4 1
Silicon Institute of Technology Sorting an Array-I
16
• If we observe the max value of the array after heapify sits at the
root.
14 10
• Idea is to remove this element from the root and heapify the tree
again from root.
• Place the removed element at the last element in the array and
8 7 9 3 decrease the heap length
2 4 1 Alg: HEAPSORT(A)
1. BUILD-MAX-HEAP(A)
2. for i ← length[A] downto 2
3. do exchange A[1] ↔ A[i]
4. Heap-Size(A) = Heap-Size(A) -1
5. MAX-HEAPIFY(A, 1)
Silicon Institute of Technology Sorting an Array-II
1 14
16
14 10 8 10
14 10
8 7 9 3 4 7 9 3
8 7 9 3
2 4 16 2 1 16
2 4 1
14 1 10
8 10 8 10 8 9
4 7 9 3 4 7 9 3 4 7 1 3
2 1 16 2 14 16 2 14 16
Silicon Institute of Technology Sorting an Array-III
10 2 9
8 9 8 9 8 3
4 7 1 3 4 7 1 3 4 7 1 2
2 14 16 10 14 16 10 14 16
9 2 8
8 3 8 3 7 3
4 7 1 2 4 7 1 9 4 2 1 9
10 14 16 10 14 16 10 14 16
Silicon Institute of Technology Sorting an Array-IV
8 1 7
7 3 7 3 4 3
4 2 1 9 4 2 8 9 1 2 8 9
10 14 16 10 14 16 10 14 16
2 4
7
4 3 2 3
4 3
1 7 8 9 1 7 8 9
1 2 8 9
10 14 16 10 14 16
10 14 16
Silicon Institute of Technology Sorting an Array-V
4 1 3
2 3 2 3 2 1
1 7 8 9 4 7 8 9 4 7 8 9
10 14 16 10 14 16 10 14 16
1 2
3
2 3 1 3
2 1
4 7 8 9 4 7 8 9
4 7 8 9
10 14 16 10 14 16
10 14 16
Silicon Institute of Technology Sorting an Array-VI
2 1
1 3 2 3
4 7 8 9 4 7 8 9
10 14 16 10 14 16
1 2 3 4 7 8 9 10 14 16
Sorted Array
Silicon Institute of Technology MAX-HEAPIFY Running Time
• Intuitively:
– It traces a path from the node to a leaf. Alg: MAX-HEAPIFY(A, i)
1. l ← LEFT(i)
– At each level it makes exactly 2 comparisons.
2. r ← RIGHT(i)
– Total number of comparisons is 2h. 3. if l ≤ Heap-Size(A) and A[l] > A[i]
– Running time is O(h) or O(lg n). 4. then largest ←l
5. else largest ←i
• Running time of MAX-HEAPIFY is O(lgn) 6. if r ≤ Heap-Size(A) and A[r] > A[largest]
7. then largest ←r
• Can be written in terms of the height of the 8. if largest i
heap, as being O(h) 9. then exchange A[i] ↔ A[largest]
10. MAX-HEAPIFY(A, largest)
• Since the height of the heap islgn
–
Silicon Institute of Technology Running Time of BUILD MAX HEAP
Alg: BUILD-MAX-HEAP(A)
1. Heap-Size(A) = length[A]
2. for i ← length[A] /2 downto 1
O(n)
3. do MAX-HEAPIFY(A, i) O(lgn)
4 7 9 3
2 8 1
Silicon Institute of Technology Running Time of BUILD MAX HEAP
• build-max-heap algorithm executes bottom-to-top.
• Let the size of heap = n
• Maxm no. of elements with height h =
∗ 𝑂(ℎ)
∞
ℎ 1/2
𝐵𝑢𝑡 ℎ = 2
=2
2 1 − 1/2
ℎ=0
= O 𝑛
Silicon Institute of Technology Total Running time of Sorting Algorithm
Alg: HEAPSORT(A)
1. BUILD-MAX-HEAP(A) O(n)
5. MAX-HEAPIFY(A, 1) O(lgn)
Priority Queues
Silicon Institute of Technology
Priority Queues
Silicon Institute of Technology Operations on Priority Queues
Max-Priority queues support the following operations:
– INSERT(S, x): inserts element x into set S
– MAXIMUM(S): returns element of S with largest key
– EXTRACT-MAX(S): removes and returns element of S with
largest key
– INCREASE-KEY(S, x, k): increases value of element x’s key to k
(Assume k ≥ x’s current key value)
– REMOVE(S,i) : Remove an element pointed by i.
Silicon Institute of Technology HEAP-MAXIMUM
Goal:
– Return the largest element of the heap
Alg: HEAP-MAXIMUM(A)
1. return A[1] Running time: O(1)
Heap-Maximum(A) returns 7
Silicon Institute of Technology HEAP-EXTRACT-MAX
Goal:
– Extract the largest element of the heap (i.e., return the max value and also remove
that element from the heap
Idea:
– Exchange the root element with the last
– Decrease the size of the heap by 1 element
– Call MAX-HEAPIFY on the new root, on a heap of size n-1
14 10 max = 16 14 10
8 7 9 3 8 7 9 3
2 4 1 2 4
Heap size decreased with 1
14
Call MAX-HEAPIFY(A, 1)
8 10
4 7 9 3
2 1
Silicon Institute of Technology HEAP-EXTRACT-MAX
Alg: HEAP-EXTRACT-MAX(A)
1. if heap-size[A] < 1
2. then error “heap underflow”
3. max ← A[1]
4. A[1] ← A[heap-size[A]]
5. heap-size[A] ← heap-size[A] - 1
16
14 10
8 i 7 9 3
Key [i] ← 15 2 4 1
Silicon Institute of Technology Example: HEAP-INCREASE-KEY
16 16
14 10 14 10
8 i 7 9 3 8 i 7 9 3
2 4 1 2 15 1
Key [i ] ← 15
16 16
i
14 10 15 10
i
15 7 9 3 14 7 9 3
2 8 1 2 8 1
Silicon Institute of Technology HEAP-INCREASE-KEY
max-heap property
Silicon Institute of Technology Example: MAX-HEAP-INSERT
Insert value 15: Increase the key to 15
- Start by inserting - Call HEAP-INCREASE-KEY on A[11] = 15
16
16
14 10
14 10
8 7 9 3
8 7 9 3
2 4 1 15
2 4 1 -
16 16
14 10 15 10
8 15 9 3 8 14 9 3
2 4 1 7 2 4 1 7 The restored heap containing
the newly added element
Silicon Institute of Technology MAX-HEAP-INSERT
14 10
1. heap-size[A] ← heap-size[A] + 1
8 7 9 3
2. A[heap-size[A]] ← - 2 4 1 -
Alg: MAX-HEAP-REMOVE(A, i)
1. X ← HEAP-MAXIMUM(A) + 1 14
2. HEAP-INCREASE-KEY(A, i , X)
3. HEAP-EXTRACT-MAX(A) 8 10
4 i 7 9 3
2 1
– MAX-HEAPIFY O(lgn)
– BUILD-MAX-HEAP O(n)
– HEAP-SORT O(nlgn)
– MAX-HEAP-INSERT O(lgn)
– HEAP-EXTRACT-MAX O(lgn)
Average
– HEAP-INCREASE-KEY O(lgn) O(lgn)
– HEAP-MAXIMUM O(1)
Silicon Institute of Technology
Thank You
Silicon Institute of Technology
Dynamic Programming
Sound familiar?
Recursion?
Problems with Recursion…
Silicon Institute of Technology Fibonacci Series: An Example
Using Recursion
Silicon Institute of Technology
Problem With Recursion
Silicon Institute of Technology Slow Fibonacci
Why so slow?
• Algorithm keeps calculating the same value over
and over
• When calculating the 40th Fibonacci number the
algorithm calculates the 4th Fibonacci number
24,157,817 times!!!
Silicon Institute of Technology Dynamic Programming: Approach
State: A state indicates the sub problem for which decision needs to be
taken.
• The variables that are used to take decision at every stage are called state variables
• Number of state variables should be as small as possible.
Silicon Institute of Technology Components of Dynamic Programming
Policy: Policy is a rule that determines the decision at each stage
• A policy is called optimal, if it is globally optimal
• This is called the Bellmann’s Principle of Optimality
Principle of Optimality
• The core principle of Dynamic Programming is ‘Principle of Optimality’
It states that the optimal sequence of decisions in a multistage decision
problem is feasible if and only if its sub-sequences are optimal
In other words
An optimal policy (a sequence of decision) has the property that whatever
the initial state and decision are, the remaining decisions must constitute
an optimal policy with regards to the state resulting from the first decision
Silicon Institute of Technology Procedure for Dynamic Programming
Step 1: Identify the objective function of the given problem
Step 2: Identify the decision variables that characterize the objective
function
Step 3: Generalisation of the problem by creating a set related similar
sub problems
Step 4: Identify the stages and state variables of the problem
Step 5: Write a recursive relation of the problem in terms of its sub
problem
Step 6: Solve the recursive relation
Step 7 : Recover and the state the final solution in terms of the result of
the sub problem
Silicon Institute of Technology Characteristic of Dynamic Programming
Overlapping Sub-problem:
• One of the main characteristics of dynamic programming is to spilt the problem
into sub-problems.
• But unlike divide and conquer approach here many subproblems overlap and
can not be treated distinctly
Two ways of handling overlapping problems
1. Memorization Technique: This method looks into a table to check
whether the table has any entry or not.
• Initially all entries are filled with NIL or undefined
• If no value is present then it is computed
• Here the computation flows in a top-down method.
Silicon Institute of Technology Characteristic of Dynamic Programming
2. Tabulation Method: Here is the problem is solved from scratch
• The smallest subproblem is solved and it is stored in the table.
• Its value is used in the table. Its value is later used later for solving larger problem
• In other words computation follows a Bottom-up method.
Optimal Substructures:
• An optimal solution to a problem contains within it an
optimal solution to sub-problems
• Optimal solution to the entire problem is build in a
bottom-up manner from optimal solutions to sub-
Each substructure is optimal.
problems
(Principle of optimality)
Silicon Institute of Technology Algorithm Fibonacci(n)
Divide and Conquer Approach
Algo Fibonacci(n)
Begin
if((n==0) OR (n==1)) then
return n
else return [ Fibonacci(n-1) + Fibonacci(n-2)]
end if
End
Silicon Institute of Technology Algorithm Fibonacci(n)
Algo mem_Fibonacci(n) // top down approach
Begin
if((n==0) OR (n==1)) then return n
else if A[n] is undefined then
A[n] = mem_Fibonacci(A[n-1]) + mem_Fibonacci(A[n-2])
return A[n]
else return A[n]
end if
End
Silicon Institute of Technology Algorithm Fibonacci(n)
Algo dp_Fibonacci(n) // bottom up approach
Begin
first = 0
second = 1
if(n==0) OR (n==1) then
return n
end if
repeat n-1 times
current = first + second
first = second
second = current
End repeat
return(current)
End
Silicon Institute of Technology Matrix-Chain Multiplication
Problem: given a sequence A1, A2, …, An , compute the product:
A1 A2 An
• The order in which we multiply the matrices has a significant impact on the cost of
evaluating the product
Silicon Institute of Technology MATRIX-MULTIPLY(A, B)
[Link] columns[A] rows[B]
2. then error “incompatible dimensions”
3. else for i 1 to rows[A]
4. do for j 1 to columns[B] rows[A] cols[A] cols[B]
multiplications
5. do C[i, j] = 0
6. for k 1 to columns[A]
7. do C[i, j] C[i, j] + A[i, k] B[k, j]
k
j cols[B]
j cols[B]
i = i
* k
A B C
rows[A]
rows[A]
Silicon Institute of Technology Matrix Compatibility for Multiplication
No of multiplications = p x q x r
Notation:
Ai…j = Ai Ai+1 Aj, i j
For i < j:
Suppose that an optimal parenthesization of Ai…j splits the product
between Ak and Ak+1, where ik<j
• Assume that the optimal parenthesization splits the product Ai Ai+1
Aj at k (i k < j)
for 1 i j n 1
n
Silicon Institute of Technology Computing the Optimal Costs (cont.)
0 if i = j
m[i, j] = min {m[i, k] + m[k+1, j] + pi-1pkpj} if i < j
ik<j
2
Compute rows from top to bottom 3
and from left to right
In a similar matrix s we keep the
optimal values of k
n
Silicon Institute of Technology Example: min {m[i, k] + m[k+1, j] + pi-1pkpj}
1 2 3 4 5 6
1
2
• Values m[i, j] depend only on
3
values that have been
previously computed 4
5
6
i
Silicon Institute of Technology Example min {m[i, k] + m[k+1, j] + pi-1pkpj}
A1 A2 A 3 A4 1 2 3 4
M[1,1] =0 1 2 3 4
M[2,2] =0 1 0
M[3,3] =0
2 0
M[4,4] =0 S
3 0
4 0
Silicon Institute of Technology Example min {m[i, k] + m[k+1, j] + pi-1pkpj}
A1 A2 A 3 A4 1 2 3 4
1 2 3 4
1 0 1 1 3
2 0 2 3 • s[1, n] = 3 A1..4 = A1..3 A4..4
3 0 3 • s[1, 3] = 1 A1..3 = A1..1 A2..3
4 0
Final Parenthesis: (A1(A2 A3) A4)
Silicon Institute of Technology MATRIX-CHAIN-ORDER(p)
1. n length[p] – 1
2. for i 1 to n Running time: (n 3)
PRINT-OPT-PARENS(s, i, j)
if i = j
1 2 3 4
then print “A i”
1 0 1 1 3
else print “(”
2 0 2 3
PRINT-OPT-PARENS(s, i, s[i, j]) 3 0 3
PRINT-OPT-PARENS(s, s[i, j] + 1, j) 4 0
print “)”
Thank You
Silicon Institute of Technology
Example
X = <A, B, C, B, D, A, B>
Z = <B, C, D, B> is a subsequence of X with index sequence (2, 3, 5, 7)
Silicon Institute of Technology Longest Common Subsequence
Formal Definition : Common Subsequence
Given two Sequences X and Y, we say that a sequence Z is a common
subsequence of X and Y if Z is a subsequence of both X and Y.
For Example: Given two sequences
X = <A, B, C, B, D, A, B> Y =<B, D, C, A, B, A>
Common Subsequence
<A, B, C, B, D, A, B> <A, B, C, B, D, A, B>
Z1= <B, C, B, A>
Z2= <B, D, A, B>
Brute-force Approach: We will find all subsequence of X and check each subsequence to see whether it
is also a subsequence of Y. (Keeping track of the longest sequence)
Note: As there are 2m possible sub sequences of X, It is going to take exponential time.
Silicon Institute of Technology Theorem
Optima Structure of LCS
Let X = <x1,x2,x3…….xm> and Y = <y1,y2,y3…….yn> be sequences. And let
Z = < z1,z2,33…….zk > be any LCS of X and Y
Xi x1 x2 … xi-1 xi
Yj y1 y2 … yj-1 yj=xi
Zk z1 z2…zk-1 zk =yj=xi
Zk is Zk -1 followed by zk = yj = xi where
Zk-1 is an LCS of Xi-1 and Yj -1 and
LenLCS(i, j)=LenLCS(i-1, j-1)+1
7
Silicon Institute of Technology Xi and Yj end with xi yj
Xi x1 x2 … xi-1 xi Xi x1 x2 … xi-1 x i
Yj y1 y2 … yj-1 yj Yj yj y1 y2 …yj-1 yj
8
Silicon Institute of Technology
C[i, j] =
Recursive Approach
Silicon Institute of Technology Writing the recurrence equation
• Let Xi denote the ith prefix x[1..i] of x[1..m], and
• X0 denotes an empty prefix
• We will first compute the length of an LCS of Xm and Yn , LenLCS(m, n),
and then use information saved during the computation for finding the
actual subsequence
• We need a recursive formula for computing LenLCS(i, j).
X = ABCBDAB
Y = BDCABA
Silicon Institute of Technology LCS Example
j 0 1 2 3 4 5 6
i Yj B D C A B A
0 Xi 0 0 0 0 0 0 0
1 A 0
2 B 0
3 C 0
4 B 0
5 D 0
6 A 0
7 B 0
Silicon Institute of Technology LCS Example
j 0 1 2 3 4 5 6
i Yj B D C A B A
0 Xi 0 0 0 0 0 0 0
1 A 0 0 0 0 1 1 1
2 B 0 1 1 1 1 2 2
3 C 0 1 1 2 2 2 2
4 B 0 1 1 2 2 3 3
5 D 0 1 2 2 2 3 3
6 A 0 1 2 2 3 3 4
7 B 0 1 2 2 3 4 4
Silicon Institute of Technology LCS Example
j 0 1 2 3 4 5 6
i Yj B D C A B A
0 Xi 0 0 0 0 0 0 0
1 A 0 0 0 0 1 1 1
2 B 0 1 1 1 1 2 2
3 C 0 1 1 2 2 2 2
4 B 0 1 1 2 2 3 3
5 D 0 1 2 2 2 3 3
6 A 0 1 2 2 3 3 4
7 B 0 1 2 2 3 4 4
Silicon Institute of Technology LCS Example
j 0 1 2 3 4 5 6
i Yj B D C A B A
0 Xi 0 0 0 0 0 0 0
1 A 0 0 0 0 1 1 1
2 B 0 1 1 1 1 2 2
3 C 0 1 1 2 2 2 2
4 B 0 1 1 2 2 3 3
5 D 0 1 2 2 2 3 3
6 A 0 1 2 2 3 3 4
7 B 0 1 2 2 3 4 4
Silicon Institute of Technology LCS Length Algorithm
Algo LCS_Length
1. m [Link]
2. n [Link]
3. Let B[1..m, 1..n] and C[1..m, 1..n] be two tables
4. for i= 0 to m
5. C[i, 0] =0
6. for j= 0 to n
7. C[0, j] =0
Silicon Institute of Technology
8. for i= 1 to m
9. for j= 1 to n
10. if ( xi == yj)
11. then C[i, j] = C[i-1, j-1]+1
12. B[i, j] = “↖”
13. else if (C[i-1, j] >= C[i, j-1])
14. then C[i, j] = C[i-1, j]
15. B[i, j] = “↑”
16. else C[i, j] = C[i, j-1]
17. B[i, j] = “←”
Silicon Institute of Technology PRINT-LCS(B,X,i,j)
Algo PRINT-LCS(B, X, i, j)
1. if i==0 OR j==0 then return
2. if B[i, j] == “↖”
3. PRINT-LCS(B, X, i-1, j-1)
4. print x
5. else if B[i, j] == “↑”
6. PRINT-LCS(B, X, i-1, j)
7. else PRINT-LCS(B, X, i, j-1)
Silicon Institute of Technology
Thank You