Daa Notes
Daa Notes
DAA-Notes
Design And Analysis Of Algorithm (Dr. A.P.J. Abdul Kalam Technical University)
Prepared By-
UNIT-1
INTRODUCTION
Review:- Elementary Data Structures, Algorithms and its complexity(Time and Space), Analysing Algorithms,
Asymptotic Notations, Priority Queue, Quick Sort.
Recurrence relation:- Methods for solving recurrence(Substitution , Recursion tree, Master theorem), Strassen
multiplication.
Topperworld.in
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
What is Algorithm
He word Algorithm means “a process or set of rules to
be followed in calculations or other problem-solving
operations”. Therefore Algorithm refers to a set of
rules/instructions that step-by-step define how a work is
to be executed upon in order to get the expected results.
Why study Algorithm ?
The importance of algorithms is very high in today's
world but in reality, what we focus on is the result, be it
ios apps, android apps, or any other application. The
reason we have these resultant applications is the
Algorithm. If programming a building, then the
algorithm is the pillar programming is standing on, and
without pillars, there is no building. But why do we go
for algorithms instead of going for the application
directly? Let's get that from an example. Let's suppose
we are building something, and we have the result in
mind. We are not an expert, but still, we bring all the
necessary items and design that thing. It also looks like
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Properties of Algorithm
All Algorithms must satisfy the following criteria -
1) Input
There are more quantities that are extremely supplied.
2) Output
At least one quantity is produced.
3) Definiteness
Each instruction of the algorithm should be clear and
unambiguous.
4) Finiteness
The process should be terminated after a finite number
of steps.
5) Effectiveness
Every instruction must be basic enough to be
carried out theoretically or by using paper and
pencil
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
6)Independent
An algorithm should have step-by-step directions, which
should be independent of any programming code. It
should be such that it could be run on any of the
programming languages.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Advantages of Algorithms:
Disadvantages of Algorithms:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Analyzing Algorithm
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
1. Sequencing:
Computation Time = tA + tB
= (max (tA,tB)
= (max (O (n), θ (n2)) = θ (n2)
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
2. If-then-else:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
3. For loop:
The general format of for loop is:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
1. for i ← 1 to n
2. {
3. P (i)
4. }
If the computation time ti for ( PI) various as a function
of "i", then the total computation time for the loop is
given not by a multiplication but by a sum i.e.
1. For i ← 1 to n
2. {
3. P (i)
4. }
Takes
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
1. For i ← 2 to n-1
2. {
3. For j ← 3 to i
4. {
5. Sum ← Sum+A [i] [j]
6. }
7. }
Solution:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
While loop:
The Simple technique for analyzing the loop is to
determine the function of variable involved whose value
decreases each time around. Secondly, for terminating
the loop, it is necessary that value must be a positive
integer. By keeping track of how many times the value
of function decreases, one can obtain the number of
repetition of the loop. The other approach for analyzing
"while" loop is to treat them as recursive algorithms.
Algorithm:
1. 1. [Initialize] Set k: =1, LOC: =1 and MAX: = DA
TA [1]
2. 2. Repeat steps 3 and 4 while K≤N
3. 3. if MAX<DATA [k],then:
4. Set LOC: = K and MAX: = DATA [k]
5. 4. Set k: = k+1
6. [End of step 2 loop]
7. 5. Write: LOC, MAX
8. 6. EXIT
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Example:
The running time of algorithm array Max of computing
the maximum element in an array of n integer is O (n).
Solution:
1. 2 + 1 + n +4 (n-1) + 1=5n
2. 2 + 1 + n + 6 (n-1) + 1=7n-2
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Asymptotic Notation
Asymptotic Notation is used to describe the running
time of an algorithm - how much time an algorithm
takes with a given input, n.
Asymptotic Notation is a
way of comparing function that ignores constant factors
and small input sizes. Three notations are used to
calculate the running time complexity of an algorithm:
There are three different notations: big O, big Theta
(Θ), and big Omega (Ω).
Why is Asymptotic Notation Important?
1. They give simple characteristics of an algorithm's
efficiency.
2. They allow the comparisons of the performances of
various algorithms.
1) Big-O Notation
The Big-O notation describes the worst-case running
time of a program. We compute the Big-O of an
algorithm by counting how many iterations an
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
For Example:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
For Example:
f (n) =8n2+2n-3≥8n2-3
=7n2+(n2-3)≥7n2 (g(n))
Thus, k1=7
Hence, the complexity of f (n) can be represented as Ω
(g (n))
3. Theta (θ) Notation: The function f (n) = θ (g (n))
[read as "f is the theta of g of n"] if and only if there exists
positive constant k1, k2 and k0 such that
k1 * g (n) ≤ f(n)≤ k2 g(n)for all n, n≥ n0
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
2. Iteration Method
4. Master Method
1. Substitution Method:
The Substitution Method Consists of two main steps:
T (n) = T +n
We have to show that it is asymptotically bound by O
(log n).
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Solution:
For T (n) = O (log n)
We have to show that for some constant c
1. T (n) ≤c logn.
Put this in given Recurrence Equation.
T (n) ≤c log + 1
≤c log + 1 = c logn-clog2 2+1
≤c logn for c≥1
Thus T (n) =O logn.
Example2. Consider the Recurrence
T (n) = 2T + n n>1
Find an Asymptotic bound on T.
Solution:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
2. Iteration Methods
It means to expand the recurrence and express it as a
summation of terms of n and initial condition.
Example1: Consider the Recurrence
1. T (n) = 1 if n=1
2. = 2T (n-1) if n>1
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
4) Master Method
The Master Method is used for solving the following
types of recurrence
T (n) = a T + f (n)
In the function to the analysis of a recursive algorithm,
the constants and function take on the following
significance:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
The element with the highest value is considered the highest priority element.
However, in other cases, we can assume the element with the lowest value as the
highest priority element.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Hence, we will be using the heap data structure to implement the priority queue in
this tutorial. A max-heap is implement is in the following operations. If you want
to learn more about it, please visit max-heap and mean-heap.
A comparative analysis of different implementations of priority queue is given
below.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
If there is no node,
create a newNode.
insert the newNode at the end (last node from left to right.)
For Min Heap, the above algorithm is modified so that parentNode is always smaller
than newNode .
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
remove noteToBeDeleted
For Min Heap, the above algorithm is modified so that the both childNodes are
smaller than currentNode .
Peek operation returns the maximum element from Max Heap or minimum
element from Min Heap without deleting the node.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
return rootNode
Extract-Max returns the node with maximum value after removing it from a Max
Heap whereas Extract-Min returns the node with minimum value after removing it
from Min Heap.
Java
C++
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
array.remove(size - 1)
arr = []
insert(arr, 3)
insert(arr, 4)
insert(arr, 9)
insert(arr, 5)
insert(arr, 2)
deleteNode(arr, 4)
print("After deleting an element: " + str(arr))
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Heap Sort
Binary Heap:
Binary Heap is an array object can be viewed as
Complete Binary Tree. Each node of the Binary Tree
corresponds to an element in an array.
1. Length [A],number of elements in array
2. Heap-Size[A], number of elements in a heap stored
within array A.
The root of tree A [1] and gives index 'i' of a node that
indices of its parents, left child, and the right child can be
computed.
1. PARENT (i)
2. Return floor (i/2)
3. LEFT (i)
4. Return 2i
5. RIGHT (i)
6. Return 2i+1
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
The index of 20 is 1
48.3M
953
Exception Handling in Java - Javatpoint
Next
Stay
To find the index of the left child, we calculate 1*2=2
This takes us (correctly) to the 14.
Now, we go right, so we calculate 2*2+1=5
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Heapify Method:
1. Maintaining the Heap Property: Heapify is a
procedure for manipulating heap Data Structure. It is
given an array A and index I into the array. The subtree
rooted at the children of A [i] are heap but node A [i]
itself may probably violate the heap property i.e. A [i] <
A [2i] or A [2i+1]. The procedure 'Heapify' manipulates
the tree rooted as A [i] so it becomes a heap.
MAX-HEAPIFY (A, i)
1. l ← left [i]
2. r ← right [i]
3. if l≤ heap-size [A] and A[l] > A [i]
4. then largest ← l
5. Else largest ← i
6. If r≤ heap-size [A] and A [r] > A[largest]
7. Then largest ← r
8. If largest ≠ i
9. Then exchange A [i] A [largest]
10. MAX-HEAPIFY (A, largest)
Analysis:
The maximum levels an element could move up are Θ
(log n) levels. At each level, we do simple comparison
which O (1). The total time for heapify is thus O (log n).
Building a Heap:
BUILDHEAP (array A, int n)
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Priority Queue:
As with heaps, priority queues appear in two forms: max-
priority queue and min-priority queue.
A priority queue is a data structure for maintaining a set
S of elements, each with a combined value called a key.
A max-priority queue guides the following operations:
INSERT(S, x): inserts the element x into the set S,
which is proportionate to the operation S=S∪[x].
MAXIMUM (S) returns the element of S with the
highest key.
EXTRACT-MAX (S) removes and returns the element
of S with the highest key.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
1. A= (15,13,9,5,12,8,7,4,0,6,2,1)
Fig: Operation of HEAP-INCREASE-KEY
Fig: (a)
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Fig: (b)
Fig: (c)
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
After one iteration of the while loop of lines 4-6, the node
and its parent have exchanged keys, and the index i
moves up to the parent.
Fig: (d)
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
HEAP-DELETE (A, i)
1. A [i] ← A [heap-size [A]]
2. Heap-size [A] ← heap-size [A]-1
3. MAX-HEAPIFY (A, i)
Quick sort
It is an algorithm of Divide & Conquer type.
Divide: Rearrange the elements and split arrays into two
sub-arrays and an element in between search that each
element in left sub array is less than or equal to the
average element and each element in the right sub- array
is larger than the middle element.
Conquer: Recursively, sort two sub arrays.
Combine: Combine the already sorted array.
• Quick Sort is a famous sorting algorithm.
• It sorts the given data items in ascending order.
Algorithm:
1. QUICKSORT (array A, int m, int n)
2. 1 if (n > m)
3. 2 then
4. 3 i ← a random index from [m,n]
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Step-01:
Initially-
• Left and Loc (pivot) points to the first element of
the array.
• Right points to the last element of the array.
Step-02:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Step-03:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Step-04:
Step-05:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Step-06:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Step-07:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Step-08:
Step-09:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Now,
• loc, left and right points at the same element.
• This indicates the termination of procedure.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
separately.
• If the array is split approximately in half (which is
log2n = O(nlog2n).
Advantages of Quick Sort-
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
size J.
• T(N-J) = Time Complexity of Quick Sort for input
of size N-J.
• M(N) = Time Complexity of finding the pivot
J is from 0 to N-1
On solving for T(N), we will find the time complexity
of Quick Sort.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
O(Nlog(N))
•
color
• time complexity will be O(NlogN)
Explanation
Lets T(n) be the time complexity for best cases
n = total number of elements
then
T(n) = 2*T(n/2) + constant*n
2*T(n/2) is because we are dividing array into two array of equal size
constant*n is because we will be traversing elements of array in each level of tree
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
therefore,
T(n) = 2*T(n/2) + constant*n
further we will devide arrai in to array of equalsize so
T(n) = 2*(2*T(n/4) + constant*n/2) + constant*n == 4*T(n/4) + 2*constant*n
therefore,
T(n) = n * T(1) + n*logn = O(n*log2(n))
O(N^2)
•
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
put n = n-1
(n-1)*T(n-1) = 2*[\sum_{i=1}^{n-2} T(i)] ............(2)
substract 1 and 2
then we will get
n*T(n) - (n-1)*T(n-1) = 2*T(n-1) + c*n^2 + c*(n-1)^2
n*T(n) = T(n-1)[2+n-1] + 2*c*n - c
n*T(n) = T(n-1)*(n+1) + 2*c*n [removed c as it was constant]
put n = n-1,
T(n-1)/n = T(n-2)/(n-1) + 2*c/n ............(4)
put n = n-2,
T(n-2)/n = T(n-3)/(n-2) + 2*c/(n-1) ............(5)
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
T(n) = log(n)*(n+1)
therefore,
T(n) = O(n*log(n))
Space Complexity
• O(N)
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
T(n) = aT(n/b) + cn
Example
Example: T(n) = 2T(n/2) + n
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Example 1
Consider T (n) = 2T + n2
We have to obtain the asymptotic bound using recursion
tree method.
Solution: The Recursion tree for the above recurrence is
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
T (n) = 4T +n
Obtain the asymptotic bound using recursion tree
method.
Solution: The recursion trees for the above recurrence
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
When we add the values across the levels of the recursion trees, we get a value of n for every
level. The longest path from the root to leaf is
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Master Theorem-
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Case-01:
Case-02:
If a = bk and
• If p < -1, then T(n) = θ (nlogba)
• If p = -1, then T(n) = θ (n
log a 2
b .log n)
• If p > -1, then T(n) = θ (n
log a p+1
b .log n)
Case-03:
If a < bk and
• If p < 0, then T(n) = O (nk)
• If p >= 0, then T(n) = θ (n log n)
k p
Problem-01:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Solution-
Now, a = 3 and bk = 22 = 4.
Clearly, a < bk.
So, we follow case-03.
Since p = 0, so we have-
T(n) = θ (nklogpn)
T(n) = θ (n2log0n)
Thus,
T(n) = θ (n2)
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Problem-02:
Solution-
Now, a = 2 and bk = 21 = 2.
Clearly, a = bk.
So, we follow case-02.
Since p = 1, so we have-
T(n) = θ (nlogba.logp+1n)
T(n) = θ (nlog22.log1+1n)
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Thus,
T(n) = θ (nlog2n)
Problem-03:
Solution-
Since p = 0, so we have-
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
T(n) = θ (nklogpn)
T(n) = θ (n0.51log0n)
Thus,
T(n) = θ (n0.51)
Problem-04:
Solution-
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
So, we have-
T(n) = θ (nlogba)
T(n) = θ (nlog2√2)
T(n) = θ (n1/2)
Thus,
T(n) = θ (√n)
Problem-05:
Solution-
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Problem-06:
Solution-
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Now, a = 3 and bk = 31 = 3.
Clearly, a = bk.
So, we follow case-02.
Since p = 0, so we have-
T(n) = θ (nlogba.logp+1n)
T(n) = θ (nlog33.log0+1n)
T(n) = θ (n1.log1n)
Thus,
T(n) = θ (nlogn)
Problem-07:
A(n)
{
if(n<=1)
return 1;
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
else
return A(√n);
}
Solution-
Let-
n = 2m ……(1)
Then-
T(2m) = T(2m/2) + 1
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
So, we have-
S(m) = S(m/2) +1
Now, we can easily apply Master’s Theorem.
Now, a = 1 and bk = 20 = 1.
Clearly, a = bk.
So, we follow case-02.
Since p = 0, so we have-
S(m) = θ (mlogba.logp+1m)
S(m) = θ (mlog21.log0+1m)
S(m) = θ (m0.log1m)
Thus,
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Now,
• From (1), we have n = 2m.
• So, logn = mlog2 which implies m = log2n.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
UNIT-2
Greedy algorithms:- Elements , Activity- Selection problem, Huffman codes, Task scheduling problem, Travelling
Salesman Problem.
Advanced data Structures:- Binomial heaps, Fibonacci heaps, Splay Trees, Red-Black Trees.
Topperworld.in
Dynamic Programming:-
Dynamic Programming is a technique in computer
programming that helps to efficiently solve a class of
problems that have overlapping subproblems
and optimal substructure property.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
b.Bottom up approach
It is also termed as tabulation technique. In this,
all subproblems are needed to be solved in
advance and then used to build up a solution to
the larger problem.
2. Optimal sub structure
It implies that the optimal solution can be obtained
from the optimal solution of its subproblem. So
optimal substructure is simply an optimal selection
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
C[i, 0] := 0
for j = 1 to n do
C[0, j] := 0
for i = 1 to m do
for j = 1 to n do
if xi = yj
C[i, j] := C[i - 1, j - 1] + 1
B[i, j] := ‘D’
else
if C[i -1, j] ≥ C[i, j -1]
C[i, j] := C[i - 1, j] + 1
B[i, j] := ‘U’
else
C[i, j] := C[i, j - 1]
B[i, j] := ‘L’
return C and B
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Example: Given two sequences X [1...m] and Y [1.....n]. Find the longest
common subsequences to both.
That is:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Step 4: Constructing an LCS: The initial call is PRINT-LCS (b, X, X.length, Y.length)
PRINT-LCS (b, x, i, j)
1. if i=0 or j=0
2. then return
3. if b [i,j] = ' ↖ '
4. then PRINT-LCS (b,x,i-1,j-1)
5. print x_i
6. else if b [i,j] = ' ↑ '
7. then PRINT-LCS (b,X,i-1,j)
8. else PRINT-LCS (b,X,i,j-1)
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
From the table we can deduct that LCS = 6. There are several such sequences, for instance
(1,0,0,1,1,0) (0,1,0,1,0,1) and (0,0,1,1,0,1)
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
1. n length[p]-1
2. for i ← 1 to n
3. do m [i, i] ← 0
4. for l ← 2 to n // l is the chain length
5. do for i ← 1 to n-l + 1
6. do j ← i+ l -1
7. m[i,j] ← ∞
8. for k ← i to j-1
9. do q ← m [i, k] + m [k + 1, j] + pi-1 pk pj
10. If q < m [i,j]
11. then m [i,j] ← q
12. s [i,j] ← k
13. return m and s.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Let us proceed with working away from the diagonal. We compute the optimal solution for
the product of 2 matrices.
2. m (2, 3) = m2 x m3
= 10 x 3 x 3 x 12
= 10 x 3 x 12 = 360
3. m (3, 4) = m3 x m4
= 3 x 12 x 12 x 20
= 3 x 12 x 20 = 720
4. m (4,5) = m4 x m5
= 12 x 20 x 20 x 7
= 12 x 20 x 7 = 1680
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
M [1, 3] =264
As Comparing both output 264 is minimum in both cases
so we insert 264 in table and ( M1 x M2) + M3 this
combination is chosen for the output making.
M [2, 4] = M2 M3 M4
1. There are two cases by which we can solve this
multiplication: (M2x M3)+M4, M2+(M3 x M4)
2. After solving both cases we choose the case in which
minimum output is there.
M [2, 4] = 1320
As Comparing both output 1320 is minimum in both
cases so we insert 1320 in table and M2+(M3 x M4) this
combination is chosen for the output making.
M [3, 5] = M3 M4 M5
1. There are two cases by which we can solve this
multiplication: ( M3 x M4) + M5, M3+ ( M4xM5)
2. After solving both cases we choose the case in which
minimum output is there.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
M [3, 5] = 1140
As Comparing both output 1140 is minimum in both
cases so we insert 1140 in table and ( M3 x M4) + M5this
combination is chosen for the output making.
M [1, 4] =1080
As comparing the output of different cases then '1080' is
minimum output, so we insert 1080 in the table and
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
M [2, 5] = 1350
As comparing the output of different cases then '1350' is
minimum output, so we insert 1350 in the table and M2 x(
M3 x M4 xM5)combination is taken out in output making.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
M [1, 5] = 1344
As comparing the output of different cases then '1344' is
minimum output, so we insert 1344 in the table and M1 x
M2 x(M3 x M4 x M5)combination is taken out in output
making.
Final Output is:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Greedy Algorithm
A greedy algorithm is an approach for solving a
problem by selecting the best option available at the
moment. It doesn't worry whether the current best result
will bring the overall optimal result.
The algorithm never reverses the earlier decision even if
the choice is wrong. It works in a top-down approach.
This algorithm may not produce the best result for all
the problems. It's because it always goes for the local
best choice to produce the global best result.
2. Optimal Substructure
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
If the optimal overall solution to the problem corresponds to the optimal solution to
its subproblems, then the problem can be solved using a greedy approach. This
property is called optimal substructure.
i) Huffman Coding
ii) Knapsack problem
iii) Activity Selection Problem (ASP)
iv) Travelling Salesman Problem (TSP)
v) Task Scheduling
Huffman Coding is generally useful to compress the data in which there are
frequently occurring characters.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
a 0
b 101
c 100
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
d 111
e 1101
f 1100
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
1. a: 50 b: 25 c: 15 d: 40 e: 75
Solution:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
i.e.
48.8M
785
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
2) Knapsack Problem:
The knapsack problem is a problem in combinational
optimization : Given a set of items, each with a weight
and a value, determine the number of each item to
include in a collection so that the total weight is less than
or equal to a given limit and the total value is as large as
possible.
For example, the weight of the container is 20 kg. We
have to select the items in such a way that the sum of the
weight of items should be either smaller than or equal to
the weight of the container, and the profit should be
maximum.
Maximize ∑n=1n ( xi . pi)
subject to constraint,
∑n=1n ( xi . wi ) ⩽ W
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Algorithm: Greedy-Fractional-Knapsack (w [
1..n], p[1..n], W)
for i = 1 to n
do x[i] = 0
weight = 0
for i = 1 to n
if weight + w[i] ≤ W then
x[i] = 1
weight = weight + w[i]
else
x[i] = (W - weight) / w[i]
weight = W
break
return x
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
S = { I2 }, SW = 15, SP = 0 + 25 = 25
Iteration 2 : SW + w1 > M, so break down item I1.
The remaining capacity of the knapsack is 5 unit, so
select only 5 units of item I1.
frac = (M – SW) / W[i] = (20 – 15) / 18 = 5 / 18
S = { I2, I1 * 5/18 }
SP = SP + v1 * frac = 25 + (24 * (5/18)) = 25 + 6.67 =
31.67
SW = SW + w1 * frac = 15 + (18 * (5/18)) = 15 + 5 =
20
The knapsack is full. Fractional Greedy
algorithm selects items { I2, I1 * 5/18 }, and it gives a
profit of 31.67 units.
Problem: Find the optimal solution for knapsack problem (fraction) where
knapsack capacity = 28, P = {9, 5, 2, 7, 6, 16, 3} and w = {2, 5, 6, 11, 1, 9, 1}.
Solution:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
1. n ← length [s]
2. A ← {1}
3. j ← 1.
4. for i ← 2 to n
5. do if si ≥ fi
6. then A ← A ∪ {i}
7. j ← i
8. return A
Example: Given 10 activities along with their start and end time as
S = (A1 A2 A3 A4 A5 A6 A7 A8 A9 A10)
Si = (1,2,3,4,7,8,9,9,11,12)
fi = (3,5,4,7,10,9,11,13,12,14)
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Now, schedule A1
Skip A5 as it is interfering.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
1 2 3 4 5 6
di 4 2 4 3 1 4
wi 70 60 50 40 30 20
Solution: According to the Greedy algorithm we sort the jobs in decreasing order of their
penalties so that minimum of penalties will be charged.
In this problem, we can see that the maximum time for which uniprocessor machine will run
in 6 units because it is the maximum deadline.
w5 + w6 = 30 + 20 = 50 (2 3 4 1 7 5 6)
Other schedule is
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
(2 4 1 3 7 5 6)
costij =
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
The tour starts from area H1 and then select the minimum cost area reachable from H1.
Mark area H6 because it is the minimum cost area reachable from H1 and then select minimum
cost area reachable from H6.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Mark area H7 because it is the minimum cost area reachable from H6 and then select minimum
cost area reachable from H7.
Mark area H8 because it is the minimum cost area reachable from H8.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Mark area H5 because it is the minimum cost area reachable from H5.
Mark area H2 because it is the minimum cost area reachable from H2.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Mark area H3 because it is the minimum cost area reachable from H3.
Mark area H4 and then select the minimum cost area reachable from H4 it is H1.So, using the
greedy strategy, we get the following.
4 3 2 4 3 2 1 6
H1 → H6 → H7 → H8 → H5 → H2 → H3 → H4 → H1.
Binomial heaps
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Binomial tree
A binomial heap is implemented as a collection of binomial
trees (compare with a binary heap, which has a shape of a
single binary tree). A binomial tree is defined recursively:
• A binomial tree of order 0 is a single node
➢ Max-Heap :
In this heap, the key value of a node is greater than or equal to
the key value of the highest child.
Hence, H[Parent(i)] ≥ H[i]
• Max Heap conforms to the above properties of heap.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Min- heap:
In mean-heap, the key value of a node is lesser than or equal
to the key value of the lowest child.
Hence, H[Parent(i)] ≤ H[i]
In this context, basic operations are shown below with respect
to Max-Heap. Insertion and deletion of elements in and from
heaps need rearrangement of elements.
Hence, Heapify function needs to be called
• Min Heap conforms to the above properties of heap.
• In min heap, every node contains lesser value element
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
1. Ordering
Nodes must be arranged in an order according to values. The
values should follow min-heap or max-heap property.
In min-heap property, the value of each node, or child, is
greater than or equal to the value of its parent, with the
minimum value at the root node.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Min-heap
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Max-heap
2. Structural
All levels in a heap should be full. In other words, it should be
a complete binary tree:
• All levels of heap should be full, except the last one.
• Nodes or child must be filled from left to right strictly.
• Heap doesn't follow binary search tree principle. The
values in right and left child or nodes don't matter.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Fibonacci Heap :
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Splaying
After an element is accessed, the splay operation is
performed, which brings the element to the root of the tree. If
the element is not in a root position, splaying can take one of
three patterns:
1. Zig (or zag) step
2. Zig-zig (or zag-zag) step
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
and the node is left of the parent), the operation is either zig-
zig (left) or zag-zag (right).
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Example
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
The tree above ensures that every path from the root to a leaf node has the same
amount of black nodes. In this case, there is one (excluding the root node).
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
UNIT-3
GRAPH ALGORITHMS
Review of graph algorithms:-Traversal Methods(Depth first and Breadth first search),Topological sort, Strongly connected components,
Minimum spanning trees- Kruskal and Prims, Single source shortest paths, Relaxation, Dijkstras Algorithm, Bellman- Ford algorithm,
Single source shortest paths for directed acyclic graphs, All pairs shortest paths- shortest paths and matrix multiplication, Floyd-
Warshall algorithm.
Computational Complexity:-Basic Concepts, Polynomial Vs Non-Polynomial Complexity, NP- hard and NP-complete classes.
Topperworld.in
Graph:-
It is a non -linear , non – primitive data
structure i.e. represented with a set of verticle that are
connected by edge i.e. G (V , e)
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Classification of Graph
Term Description
Vertex Every individual data element is called a vertex or a node. In the above image,
Edge (Arc) It is a connecting link between two nodes or vertices. Each edge has two ends
Self-loop An edge is called a self-loop if its two endpoints coincide with each other.
Adjacency Vertices are said to be adjacent to one another if there is an edge connecting them.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Algorithm of BFS :
Algorithm of BFS ( G , s)
3.d[u] := ∞
4. π[u]=NIL
6.d[s]= NIL
7. d[s]:= NIL
8.Q= ɸ
9. ENQUEUE =( Q,s)
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
10.while (Q ≠ ɸ)
11.{ u=DEQUEUE(Q)
15.d[v]=d[u]+1
16.π[v]=u
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
So, we continue doing like this, and further iterations looks like as
follows:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Initial Graph
The strongly connected components of the above graph are:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
You can observe that in the first strongly connected component, every vertex can
reach the other vertex through the directed path.
1.Algorithm of DFS ( G )
2.for each vertex u ∈ V[G]
3.color u =WHITE
4.π[u]=NIL
5.Time =0;
6.for each value u ∈ V[G]
7.if ( color [u]= WHITE
8.DFS -VISIT (G ,u )
Algo DFS VISIT ( G , u )
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
the nodes u.
Starting node: A
Step 1: Create an adjacency list for the above graph.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Step 4: Pop ‘A’ and push ‘B’ and ‘F’. Mark node ‘A’
as the visited node
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Step 7: pop ‘C’ and push ‘E’. Mark ‘C’ as a visited node.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Step 8: pop ‘E’. Mark ‘E’ as a visited node. No new node is left.
Step 9: pop ‘B’. Mark ‘B’ as visited. All the nodes in the graph are visited now.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
An undirected graph is a graph in which the edges do not point in any direction
(ie. the edges are bidirectional).
Undirected Graph
A connected graph is a graph in which there is always a path from a vertex to any
other vertex.
Connected Graph
Spanning tree
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Weighted graph
The possible spanning trees from the above graph are:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Kruskal's Algorithm :
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Algorithm of Kruskal :
1.{ constant a min -heap out of thr edge cost using
HEAPIFY
2. fir I =1 to n ;
3. do parent [i] =1 // each vertex is in a different set
4. i=0; min cost =0;
5. while ( ( i<n-1) && ( heap not empty)) do
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
6.{ Delete 0 min cost edge (u,v) from the heap & re-
heapify using ADJUST
7. j= FIND (u) ,k = FIND (v)
8.if ( j ≠ k)
9. { i= i+1
10. t [ i ,1] =u , t[i,z]=v;
11. Min cost = min cost + cost ( u, v)
12. UNION (j , k);
13.}}
14. if (i≠ n-1) then write ( No spanning Tree is possible else return
Min cost
15.}
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Prims Algorithm
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Solution-
Step-01:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Step-02:
Step-03:
Step-04:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Step-05:
Step-06:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Problem-02:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Solution-
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
1) Dijkstra’s Algorithm,
2) Bellman Ford Algorithm
b) ALGORITHM RELAXATION ( u , v , w)
1.if d[v]> d[u] + w[ u , v]
2.then d[v]=d[u]+w[u ,v]
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Here,
W= denotes the weight of the edges
r = Source code
t= destination node
u = any intermediate node
1.for I =1to n do
2 { r [ i ] = false , dist [ i ] = cost [ v , i] } //
initialize s
3. r[v]=true , dist[v]=0.0 // put v in s
4.for sum = 2 to n-1 do // determine “ n-1”
path from
5.{ choose ‘u’ among those vertex not in ‘s’
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
In this algorithm ,
v = source node
u = intermediate node
cost = the weight of the edge
d = distance from source node
n= total no. of vertice
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
The algorithm will generate the shortest path from node 0 to all the other nodes
in the graph.
Note : For this graph, we will assume that the weight of the edges represents the
distance between two nodes.
We will have the shortest path from node 0 to node 1, from node 0 to node 2,
from node 0 to node 3, and so on for every node in the graph.
Initially, we have this list of distances (please see the list below):
• The distance from the source node to itself is 0. For this example, the
source node will be node 0 but it can be any node that you choose.
• The distance from the source node to all other nodes has not been
determined yet, so we use the infinity symbol to represent this initially .
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
We also have this list (see below) to keep track of the nodes that have not been
visited yet (nodes that have not been included in the path):
Note: Since we are choosing to start at node 0, we can mark this node as visited.
Equivalently, we cross it off from the list of unvisited nodes and add a red
border to the corresponding node in diagram:
Now we need to start checking the distance from node 0 to its adjacent nodes.
As you can see, these are nodes 1 and 2 (see the red edges):
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
• Select the node that is closest to the source node based on the current
known distances.
• Mark it as visited.
• Add it to the path.
If we check the list of distances, we can see that node 1 has the shortest distance
to the source node (a distance of 2), so we add it to the path.
In the diagram, we can represent this with a red edge:
We mark it with a red square in the list to represent that it has been "visited" and
that we have found the shortest path to this node:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Now we need to analyze the new adjacent nodes to find the shortest
path to reach them. We will only analyze the nodes that are adjacent
to the nodes that are already part of the shortest path (the path
marked with red edges).
Node 3 and node 2 are both adjacent to nodes that are already in the
path because they are directly connected to node 1 and node 0,
respectively, as you can see below. These are the nodes that we will
analyze in the next step.
Since we already have the distance from the source node to node 2 written down
in our list, we don't need to update the distance this time. We only need to
update the distance from the source node to the new adjacent node (node 3):
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Now that we have the distance to the adjacent nodes, we have to choose which
node will be added to the path. We must select the unvisited node with the
shortest (currently known) distance to the source node.
From the list of distances, we can immediately detect that this is node 2 with
distance 6:
We add it to the path graphically with a red border around the node and a red
edge:
We also mark it as visited by adding a small red square in the list of distances
and crossing it off from the list of unvisited nodes:
Now we need to repeat the process to find the shortest path from the source
node to the new adjacent node, which is node 3.
You can see that we have two possible paths 0 -> 1 -> 3 or 0 -> 2 -> 3. Let's see
how we can decide which one is the shortest path.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Node 3 already has a distance in the list that was recorded previously (7, see the
list below). This distance was the result of a previous step, where we added the
weights 5 and 2 of the two edges that we needed to cross to follow the path 0 ->
1 -> 3.
But now we have another alternative. If we choose to follow the path 0 -> 2 ->
3, we would need to follow two edges 0 -> 2 and 2 -> 3 with
weights 6 and 8, respectively, which represents a total distance of 14.
Clearly, the first (existing) distance is shorter (7 vs. 14), so we will choose to
keep the original path 0 -> 1 -> 3. We only update the distance if the new
path is shorter.
Therefore, we add this node to the path using the first alternative: 0 -> 1 -> 3.
We mark this node as visited and cross it off from the list of
unvisited nodes:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
We need to check the new adjacent nodes that we have not visited so far. This
time, these nodes are node 4 and node 5 since they are adjacent to node 3.
We update the distances of these nodes to the source node, always trying to find
a shorter path, if possible:
• For node 4: the distance is 17 from the path 0 -> 1 -> 3 -> 4.
• For node 5: the distance is 22 from the path 0 -> 1 -> 3 -> 5.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
For node 5:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
• The first option is to follow the path 0 -> 1 -> 3 -> 5, which has a distance
of 22 from the source node (2 + 5 + 15). This distance was already
recorded in the list of distances in a previous step.
• The second option would be to follow the path 0 -> 1 -> 3 -> 4 -> 5,
which has a distance of 23 from the source node (2 + 5 + 10 + 6).
Clearly, the first path is shorter, so we choose it for node 5.
For node 6:
• The path available is 0 -> 1 -> 3 -> 4 -> 6, which has a distance
of 19 from the source node (2 + 5 + 10 + 2).
We mark the node with the shortest (currently known) distance as visited. In this case,
node 6.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Only one node has not been visited yet, node 5. Let's see how we can
include it in the path.
There are three different paths that we can take to reach node 5 from
the nodes that have been added to the path:
• Option 1: 0 -> 1 -> 3 -> 5 with a distance of 22 (2 + 5 + 15).
• Option 2: 0 -> 1 -> 3 -> 4 -> 5 with a distance of 23 (2 + 5 + 10
+ 6).
• Option 3: 0 -> 1 -> 3 -> 4 -> 6 -> 5 with a distance of 25 (2 + 5
+ 10 + 2 + 6).
We select the shortest path: 0 -> 1 -> 3 -> 5 with a distance of 22.
We mark the node as visited and cross it off from the list of
unvisited nodes:
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
And voilà! We have the final result with the shortest path from
node 0 to each node in the graph.
In the diagram, the red lines mark the edges that belong to the
shortest path. You need to follow these edges to follow the shortest
path to reach a given node in the graph starting from node 0.
2. Bellman-Ford algorithm
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
do
5. { for each ( i, u) in the graph do
6.{ if ( do[u] > d[i] + cost [i, u]
Then d[u]=d[i] + cost [i, u]
7.}}}
In this Algorithm
➢ Bellman Ford algorithm helps us find the shortest path from a vertex to all
other vertices of a weighted graph.
By doing this repeatedly for all vertices, we can guarantee that the result is
optimized.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
5. d [x] ← 2
1. adj [t] → r, x
2. 3 + 1 < ∞
3. d [r] ← 4
4. 3 + 5 ≤ 2
1. adj [x] → y
2. 2 - 3 < ∞
3. d [y] ← -1
1. adj [y] → r
2. -1 + 4 < 4
3. 3 <4
4. d [r] ← 3
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Computational complexity
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
i = 1; 1s
while( i<=10) 11s
{
result = i * a; 10s
printf(“\n” /d”, result); 10s
i++; 10s
}
Execution Time : 43s
Memory (Space) : 6 Bytes
NP -hard:
An NP-hard problem is at least as hard as the hardest
problem in NP and it is the class of the problems such
that every problem in NP reduces to NP-hard.
NP- Complete
NP-complete problem, any of a class of computational
problems for which no efficient solution algorithm has been
found.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
UNIT-4
Topperworld.in
Flow Network:
Flow Network is a directed graph that
is used for modeling material Flow.
There are two different vertices; one is
a source which produces material at some steady rate,
and another one is sink which consumes the content at
the same constant speed.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
The value of the flow is the net flow from the source,
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Comparison Networks
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
That is, each edge of the residual network, or residual edge, can
admit a strictly positive net flow.
Augmenting Path: Given a flow network G = (V, E) and a
flow f, an augmenting path p is a simple path from s to t in the
residual networkGf. By the solution of the residual network,
each edge (u, v) on an augmenting path admits some additional
positive net flow from u to v without violating the capacity
constraint on the edge.
Let G = (V, E) be a flow network with flow f. The residual
capacity of an augmenting path p is
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
A term, flow network, is used to describe a network of vertices and edges with a
source (S) and a sink (T). Each vertex, except S and T, can receive and send an
equal amount of stuff through it.
FORD-FULKERSON (G, s, t)
1. for each edge (u, v) ∈ E [G]
2. do f [u, v] ← 0
3. f [u, v] ← 0
4. while there exists a path p from s to t in the residual
network Gf.
5. do cf (p)←min? { Cf (u ,v):(u ,v)is on p}
6. for each edge (u, v) in p
7. do f [u, v] ← f [u, v] + cf (p)
8. f [u, v] ←f[ u ,v]
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
1.bool kuhn(vertex v) {
2. if (used[v]) return false;
3. used[v] = true;
4. for (vertex q adjacent to v) {
5. if ((q has no pair) or kuhn(pairs[q])) {
6. pairs[q] = v;
7. return true;
8. }
9. }
10.}
11.find_max_matching {
12. for (vertex v = {
13. 1,
14. ..,
15. n
16. }) {
17. used = {
18. 0
19. };
20. kuhn(v);
21. }
22.}
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Proof
Suppose for the purpose of contradiction that the
network sorts all zero-one sequences, but there exists a
sequence of arbitrary numbers that the network does not
correctly sort. That is, there exists an input sequence ha1,a2,. .
. ,ani containing elements ai and aj such that ai < aj , but the
network places aj before ai in the output sequence. We define
a monotonically increasing function f as
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
1. A[0] < A[1] < A[2] .... A[i1] < A[i] > A[i+1] > A[i+2] > A[i+3] > ... >A[
n-1]
Where, 0 ≤ i ≤ n-1.
Before moving directly towards the algorithm of bitonic sort,
first, understand the conversion of any random sequence into a
bitonic sequence.
How to convert the random sequence into a bitonic sequence?
Consider a sequence A[ 0 ... n-1] of n elements. First, start
constructing a Bitonic sequence by using 4 elements of the
sequence. Sort the first 2 elements in ascending order and the
last 2 elements in descending order, concatenate this pair to
form a Bitonic sequence of 4 elements. Repeat this process for
the remaining pairs of the element until we find a Bitonic
sequence.
Let's understand the process to convert the random sequence
into a bitonic sequence using an example.
Suppose the elements of array are - {30, 70, 40, 80, 60, 20, 10, 50}
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Merging Network
Merging Network is the network that can join two sorted input sequences into one sorted output
sequence. We adapt BITONIC-SORTER [n] to create the merging network MERGER [n].
Given two sorted sequences, if we reverse the order of the second sequence and
then connect the two sequences, the resulting sequence is bitonic.
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)
lOMoARcPSD|37581604
Downloaded by ShashankTopperworld.in
Mishra (mishrashashank3639@gmail.com)