DAA Lecture Handouts
DAA Lecture Handouts
Algorithms
Why We Study DAA
▪ Important subject of CS
▪ Core subject
▪ Examples
▪ Google search engine
▪ Facebook
▪ YouTube
▪ Google Maps
Important Topics of DAA
• Asymptotic Notations
• Big Oh, Big Thetha, Big Omega, Little oh, little omega
• Time and Space complexity
• Divide and conquer Algorithms
• Binary search
• Quick sort
• Merge sort
• Sorting Algorithms
• Selection sort
• Insertion sort
• Bubble sort
Important Topics of DAA (cont..)
• Heap Trees
• Max heap
• Min heap
• Greedy Methods
• Knapsack
• Huffman encoding
• Job sequencing
• Dijkstra algo
• Min spanning tree
• Prims algorithm
• Kruskal algorithm
Important Topics of DAA (cont..)
• Graph Traversal
• Depth First Search (DFS)
• Breadth First Search (BFS)
• Dynamic Programming
• Multistage graph
• Travelling Salesman Problem (TSP)
• Optimal binary search tree
• Bellman Ford Algorithm for shortest path
• Hashing
• Polynomial , Non polynomial (NP), NP- hard, NP-complete
Properties of Algorithm
• An algorithm is a finite set of precise instructions for performing a computation
or for solving a problem.
Properties of algorithms:
Input:
An algorithm has input values from a specified set.
Output:
From each set of input values an algorithm produces output values from a
specified set.
The output values are the solution to the problem.
Properties of Algorithm (cont...)
Definiteness:
The steps of an algorithm must be defined precisely.
Correctness:
An algorithm should produce the correct output values for each set of input values.
Finiteness:
An algorithm should produce the desired output after a finite number of steps for any input
in the set.
Effectiveness:
It must be possible to perform each step of an algorithm exactly and in a finite amount of
time.
Generality:
The procedure should be applicable for all problems of the desired form, not just for a
particular set of input values.
Algorithms
EXAMPLE :
Describe an algorithm for finding the maximum (largest) value in a finite
sequence of integers.
• there are many instances where the largest integer in a finite sequence of
integers is required.
Algorithms
Solution of Example:
We perform the following steps.
1. Set the temporary maximum equal to the first integer in the sequence.
3. Repeat the previous step if there are more integers in the sequence.
4. Stop when there are no integers left in the sequence. The temporary maximum at this
point is the largest integer in the sequence.
Algorithm
Algorithms
Example:
• Show that Algorithm for finding the maximum element in a finite sequence of integers
has all the properties listed (properties of algorithm).
Solution:
• The input to Algorithm is a sequence of integers.
• Each step of the algorithm is precisely defined, because a finite loop, and
conditional statements occur
• To show that the algorithm is correct, we must show that when the
algorithm terminates.
Cont..
• The algorithm uses a finite number of steps, because it terminates after all the
integers in the sequence have been examined (finiteness).
• The algorithm can be carried out in a finite amount of time because each step is
either a comparison or an assignment (effectiveness).
• Defined algorithm is general, because it can be used to find the maximum of any finite
sequence of integers (Generality).
How to Analyze Algorithm
• An algorithm is finite set of instruction to solve a problem.
O(g(n)) = {f(n) :
positive constants c and n0, such
that n n0,
we have 0 f(n) cg(n) }
Asymptotic Notations
Big-Ω : best case running time of algorithm (gives lower bound)
(g(n)) = {f(n) :
positive constants c and n0, such
that n n0,
we have 0 cg(n) f(n)}
Asymptotic Notations Upper
bound
Big-θ (Big-Theta)
• We can say that ftn is greater than lower bound and lower than upper bound.
Mathematically we can write this as:
F(n)= 2n2 + n
F(n) C. g(n)
F(n) = O g (n)
2n2 + n C. g ( ? )
2n2 + n C. g (n2)
Finding upper bond
➢Find upper bond of n2+ 2n+ 1
• Divide split A down the middle into subsequences, each of size n/2
• Conquer : sort each subsequence by calling merge sort recursively
• Merge : the two sorted sequences into a single sorted list
Merge Sort
• It use recursive divide and conquer approach
Design & Analysis of
Algorithm
Merge Sort Example
7 5 2 4 1 8 3 0
7 5 2 4 1 8 3 0
77 55 22 44 1 8 3 0
7 5 2 4 1 8 3 0
Merge Sort Example (cont…)
0 1 2 3 4 5 7 8
2 4 5 7 0 1 3 8
57 57 22 44 1 8 0 3
7 5 2 4 1 8 3 0
Algorithm Merge-sort
For n = 8 For n = 16
T(n)= T(n/2) + T(n/2) + n T(n)= T(n/2) + T(n/2) + n
Put value of n in eq. Put value of n in eq.
➢There is no i/p and o/p pattern in above results. If we divide both sides by i/p
T(1)/1 = 1/1 = 1 T(1)/1 = 1
T(2) /2 = 4/2 = 2 T(2) /2 = 2
T(4)/4 = 12/4 = 3 T(4)/4 = 3
T(8)/8 = 32/8 = 4 T(8)/8 = 4
T(16)/16 = 80/16 = 5 T(16)/16 = 5
Finding Merge Sort Time Complexity (cont…)
40 55 20 30 80 25 95 50
40 55 20 30 80 25 95 50
pivot p q
40 55 20 30 80 25 95 50
pivot p q
Interchange
40 25 20 30 80 55 95 50
value of p and
pivot p q q
Quick Sort (cont…)
40 25 20 30 80 55 95 50
pivot p q
40 25 20 30 80 55 95 50
pivot p q
40 25 20 30 80 55 95 50
pivot q p
When p and q
cross each other
30 25 20 40 80 55 95 50
Replace pivot pivot
with q
Quick Sort (cont…)
30 25 20 40 80 55 95 50
pivot
30 25 20 40 80 55 95 50
pivot p q pivot p q
30 25 20 ∞ 40 80 55 95 50
pivot p q pivot p q
30 25 20 ∞ 40 80 55 50 95
pivot q p pivot p q
20 25 30 ∞ 40 80 55 50 95
pivot q p pivot q p
Quick Sort (cont…)
20 25 30 ∞ 40 80 55 50 95
pivot q p pivot q p
20 25 30 ∞ 40 50 55 80 95
pivot q p pivot q p
5 10 15 20 25 30 35
p
pivot q
5 10 15 20 25 30 35
pivot p
q
When p and q
cross each other
5 10 15 20 25 30 35
Replace pivot
pivot p with q
q
Quick Sort (worst case complexity) cont…
5 10 15 20 25 30 35
pivot p
q
5 10 15 20 25 30 35 n-1
pivot p q
When p and q
5 10 15 20 25 30 35 cross each other
Replace pivot
pivot p with q
q
5 10 15 20 25 30 35 n-2
pivot p q
Quick Sort (worst case complexity) cont…
5 10 15 20 25 30 35 n-2
pivot p q
So, our equation for worst case will be: Put value of T(n-2) from eq.4 in eq.3
n-1 = 7-1 = 6
T(n)= T (n-1) + n …………eq.1 T(n)= T(n-3)+(n-2) + (n-1) + n
n-2 = 7-2 = 5
Substitute n with n-1 in eq.1
n-3 = 7-3 = 4 .
n-4 = 7-4 = 3 T(n-1)= T (n-1)-1 + (n-1)
n-5 = 7-5 = 2 T(n-1)= T(n-2) + (n-1)……eq.2 .
n-6 = 7-6 = 1 Put value of T(n-1) from eq.2 in eq.1 T(n) = n( n+ 1)/2
n-7 = 7-7 = 0 T(n) = T (n-2)+(n-1) +n…...eq.3 = n2 + n/2
Derive the value of T(n-2) from eq.1
= n2/2 + n/2
T(n-2)= T (n-2)-1 + (n-2)
T(n-2)= T (n-3) + (n-2)……..eq.4 T(n) = O (n2 )
Binary Search Algorithm
Binary Search Algorithm
• This algorithm can be used when the list has terms occurring in order of
increasing size.
III. Else If x is greater than the mid element, then x can only lie in right half
subarray after the mid element. So we recur for right half.
5 10 15 20 25 30 35 40 45 50
5 10 15 20 25 30 35 40 45 50
30 35 40 45 50
30 35
30 35
Binary Search Algorithm Analysis
• First we need to write equation of binary search algorithm.
T(n)= T (n /2) + b …………1st iteration T(n) = T (n/ 2k ) + kb….. last iteration
T(n)= T (n / 22 ) + b + b ……. 2nd iteration T(n) = T (1) + Kb
T(n)= T (n / 23 ) + b + b + b ……. 3rd iteration T(n) = a + kb ……eq.1
T(n)= T (n / 24 ) + b + b + b + b ……. 4th iteration
We have n = 2k By putting the value of k in
eq.1
If we take log both sides. T(n) = a + b log2 n
T(n) = T (n / 24 ) + 4b……...
log2 n = log2 2k T(n) = log2 n
.
= k log2 2 T(n)= O (log2 n)
.
= k (1)
T(n) = T (n/ 2i ) + ib….. nth iteration.
Insertion sort
1. For j= 2 to n
2. Key =A[2]
3. i= j-1
4. While i>0 and A[i] > key
5. A[i+1]=A[i]
6. i=i-1
7. A[i+1] =key
Insertion Sort Analysis
Insertion Sort Problem
Worst Case
= ( n 2 )
OR
= ( n 2 )
Bubble Sort
• Sorting is ordering the elements of a Algorithm Bubble Sort
list.
10 11 8 12 16 4
Bubble Sort working
• Now bubble (i= 12), If i is greater than i+1 then swap (in our case 12>8 so we swap)
10 11 8 12 16 4
• If i is not greater than i+1 , then i+1 will be consider as bubble (in our case 12 is not greater then 16, so 16
will be bubble)
10 11 8 12 16 4
• Now bubble (i= 16), If i is greater than i+1 then swap (in our case 16>4 so we swap)
10 11 8 12 4 16
➢Here our 1st pass completes, at the end of first pass, the largest element of
array or list should be at the end of list.
Bubble Sort working
• Now we continue 2nd pass by considering bubble (i= 10), If i is greater than i+1 then swap else consider i+1 as a
bubble.
10 11 8 12 4 16
10 11 8 12 4 16
• In our case 10< 11 so 11 will consider as bubble
10 11 8 12 4 16
• Now 11 >8 so swap
10 8 11 12 4 16
• Now 11< 12 so 12 will be consider as bubble
10 8 11 12 4 16
Here 2nd pass complete
and at the end of 2nd
• Now 12 >4 so pass the second largest
we swap 10 8 11 4 12 16 element of list will be its
final position
Bubble Sort Time complexity (worst case)
• In our example we had 6 elements in array. (n=6)
• To complete our 1st pass we made 5 comparisons. (element left n-1)
11 10 12 8 16 4
10 11 8 12 4 16
To complete our 2nd pass we made 4 comparisons. (element left n-2)
10 8 11 4 12 16
T(n) = n (n-1) /2
= n2 - n/2
For worst case we will consider higher order value
T(n) = O (n2 )
Greedy Approach/Algorithm
• Greedy algorithms are designed to achieve optimum solution for a given
problem.
• In greedy algorithm approach, decisions are made from the given solution
domain.
• Follow local optimal choice at each state with intend of finding global
optimum.
• For example we have currency notes of Rs. 100, 50, 20, 10
• Total Rs. 180 (here global optimum is to collect Rs.180)
• If we use greedy approach then 1st we will pick Rs. 100 note
• Secondly we pick Rs. 50
• Third we pick RS.20
• Fourth we pick Rs. 10
• In this way we will collect RS.180, total in four steps.
Knapsack problem
• Knapsack problem use greedy technique/approach to find optimal solution.
Object Obj 1 Obj 2 Obj 3 Knapsack
capacity
profit 25 24 15 M= 20
weight 18 15 10
3) greedy for both profit & weight :
1) greedy for profit: 2) greedy for weight:
Here we use proportion of P/W
pick object 3 as its weight is 10
pick object 1 as its profit is 25 and its
weight is 18 P/W of obj 1: 25/18= 1.3
10
2 10 P/W of obj 2: 24/15= 1.6
18 Obj 3 Profit = 15
Profit = 25 P/W of obj 3: 15/10 = 1.5
Obj 1
pick object 2, as its weight is 15 pick object 2, as its P/W is 1.6
pick object 2, as its profit is 24 and its
weight is 15 10 5
Profit = (10/15) * 24 = 16 Profit =
15 5
2 Profit = (2/15) * 24 = 3.2 10 (5/10) *
Obj 2 Profit = 24 15
Obj 2 Obj 3 15= 7.5
Obj 2
pick object 3, as its P/W is 1.5
18 Total = 25 + 3.2= 28.2 Total = 15 + 16 = 31
Obj 1 Total = 24 + 7.5 = 31.5
Knapsack Algorithm Time Complexity
• Knapsack problem use greedy technique/approach to find optimal solution.
Object Obj 1 Obj 2 Obj 3 Knapsack
capacity
profit 25 24 15 M= 20
weight 18 15 10 Knapsack Algorithm
greedy for both profit & weight : For i= 1 to n n times = O(n)
calculate profit/weight
Here we use proportion of P/W
Sort object in decreasing order of P/W ratio O(n log n)
P/W of obj 1: 25/18= 1.3
For i= 1 to n
P/W of obj 2: 24/15= 1.6
if M>0 & Wi<= M then
P/W of obj 3: 15/10 = 1.5
M= M-Wi
pick object 2, as its P/W is 1.6
P = P + Pi T(n)= O(n log n)
5
5 Profit = else break;
15 (5/10) *
Obj 2 Profit = 24 15
Obj 2
15= 7.5 if M> 0 n times= O (n)
pick object 3, as its P/W is 1.5 P = P + Pi (M/Wi)
Total = 24 + 7.5 = 31.5
Job Sequencing Problem
• Job sequencing problem use greedy technique/approach to find optimal
solution.
• Given an array of jobs where every job has a deadline and associated
profit.
• if the job is finished before the deadline.
• It is also given that every job takes single unit of time, so the minimum
possible deadline for any job is 1.
• How to maximize total profit if only one job can be scheduled at a time?
Job 4 job 1
m= no. of jobs
Job 1 job 3
0 1 2 (so we search array m X n times. If we
0 1 2
have same deadlines and if no. of job
and deadline are equal then we have n
X n= n2
profit = 60 + 15 = 75 profit = 60 + 30 = 90
T(n) = O (n2 )
Huffman Coding
• Huffman coding is greedy approach.
• assigns codes to characters such that the length of the code depends on
the relative frequency or weight of the corresponding character.
• Character with higher frequency will have shorter code and character with
lower frequency will have longer code.
Why we need Huffman coding?
• We will understand the need of Huffman coding with example.
0 1 C= 110 = 3bits = 15 X 3 = 45
D= 10
D= 1111 = 4 bits = 10 X4 =40
E= 2 C (15) 15
E= 11100 = 5 bits= 2 X 5= 10
F= 3 0 1
T(n)= O (nlogn) F= 11101= 5 bits= 3 X 5= 15
5 D (10)
Huffman coding require less storage and less Total bits require to represent
transmission time. 0 1 100 character message= 210
D C A B
A B A B E
S3
G E S1 E
D C
A B
D C D C
S2 E
D C
Spanning Tree (continue)
A B
a complete graph is a simple undirected graph in
which every pair of distinct vertices is connected by
a unique edge OR we can use following formula to
check that graph is complete or not:
V(V-1)/2 edges
D C
Minimum Cost Spanning Tree
• A spanning tree of a weighted graph (G) with minimum cost is called ‘minimum
cost spanning tree’
2 2
A B A B 8 A B
8
Weighted E 4 E
4 E 4
Graph
10 D C 10 D C 10
D C 5
5 5
Spanning tree 1
Spanning tree 2
cost= 27
2 cost= 21
A B 8
4 E
D C
5
Spanning tree 3
cost= 19
Prim’s Algorithm
• Prim’s algorithm is a greedy algorithm.
• It used to find the Minimum Spanning Tree (MST) from given
weighted undirected graph.
• To find out MST we apply following steps on given weighted graph.
Step 1: Remove all loops
Step 2: Remove all parallel edges between two Nodes (vertices)
• In case of parallel edges, keep the one which has the least cost (weight)
Step 3: Choose any arbitrary node as root node
Step 4: Check outgoing edges and select the one with less cost(weight)
(repeat this step for all nodes)
• There should be no cycle
Prim’s Algorithm (Example)
Find minimum cost spanning tree of given weighted graph by using
Prim’s algorithm
5
12 8 18
A B C
13
15
7 2
17 G
1 10
D E F
9 6
10
Prim’s Algorithm (Example): step 1
Min. cost =
12+9+6+1+7+2+10= 47
Prim’s Algorithm Time Complexity
5
12 8 18
A B C
13
15
7 2
17 G
1 10
D E F
9 6
10
Kruskal’s Algorithm (Example): step 1
Step 1: Remove all loops
Kruskal’s Algorithm (Example): step 2
Step 2: Remove all parallel edges between two Nodes (vertices)
• In case of parallel edges, keep the one which has the least cost
Kruskal’s Algorithm (Example): step 3
Step 3: Arrange all edges in increasing order of weight
IN Out
C B
C
BFS Example (cont..)
1. Set pointer to starting
vertex
2. Visit the starting vertex
and mark it as visited
3. IF vertex at which we have
pointer, has adjacent
unvisited vertex
Then
visit adjacent unvisited
vertex and mark it visited,
insert it in queue
ELSE
update pointer to first
element of queue, remove
first element from queue
4. Repeat step 3 until queue
is empty and all nodes
visited
D C
E D C
BFS Example (cont..)
1. Set pointer to starting
vertex
2. Visit the starting vertex
and mark it as visited
3. IF vertex at which we have
pointer, has adjacent
unvisited vertex
Then
visit adjacent unvisited
vertex and mark it visited,
insert it in queue
ELSE
update pointer to first
element of queue, remove
first element from queue
4. Repeat step 3 until queue
is empty and all nodes
visited.
F E
DFS (Depth First Search)
• DFS is a algorithm for searching all the vertices of a graph or tree data
structure.
stack
DFS Example (Cont..)
1. Push the starting vertex into
stack and mark it visited
2. IF vertex at which we have
pointer (stack top), has
adjacent unvisited vertex
Then
visit adjacent unvisited vertex
mark it visited,
push it into stack,
move pointer to top element
of stack
ELSE
Pop top element of stack
3. Repeat step 2 until stack is
empty
D
B
A stack
DFS Example (Cont..)
1. Push the starting vertex into
stack and mark it visited
2. IF vertex at which we have
pointer (stack top), has
adjacent unvisited vertex
Then
visit adjacent unvisited vertex
mark it visited,
push it into stack,
move pointer to top element
of stack
ELSE
Pop top element of stack
3. Repeat step 2 until stack is
empty
A stack
Dijkstra’s Algorithm
B C
10 3 8
A
5
2 G
4 6 1
10
D E F
9 6
2
Dijkstra’s Algorithm
Step 1: Remove all loops
Step 2: Remove all parallel edges between two Nodes (vertices)
In case of parallel edges, keep the one which has the least weight
C 10 13 inf inf
B 10 13 12 18
E 13 12 18
F 12 14
G 14
Dijkstra’s Algorithm (Method-2)
1. Remove all loops and parallel edges
1 2. set 0 value to the source vertex &
3
2 infinite value to remaining vertices
∞B ∞ E
3. Update the value of vertices by Edge
1
relaxation.
0A 1
We perform edge relaxation if:
3 1 2
d[u] + w(u,v) is less than d[v]
2 5
4 ∞C
∞D 3 Vertex from where
Weight of edge
Vertex at which we
3 we want to move
between u and v
reached
vertices
2
Then
d[v]= d[u] + w(u,v) else d[v] = d[v]
Perform edge relaxation until all the vertices
visited.
Binary Search Tree
• Keep in mind that there is a difference between “Binary Tree (BT)” and
“Binary Search Tree (BST)”
2 50
A B C
40
5 G
1
D E F
3 6
Understanding Dynamic Programing with Fibonacci series
f(4)
• For example: n=0 1 2 3 4 5 6
f (3) f(2)
f(n)= 0 1 1 2 3 5 8
f(2) f(1) f(1) f(0)
f(1) f(0)
Network Flow
• A flow network is defined as a directed graph involving a source and a sink
and several other nodes connected with edges.
10 5
A B C
8
4 7 6
G
3
E
6
Ford-Fulkerson algorithm
• Choose an arbitrary
path from source to
sink
• Find bottle neck
Flow =5 capacity of selected
path (that will be our
flow)
• Write down bottle
neck capacity with
capacity of edges of
selected path
• Find out residual
capacity
Flow =5
Flow =5
Ford-Fulkerson algorithm
Flow =5
Flow =5 + 3
4- If p [1….m] == T[i+1….s+m]
T= 0 1 0 0 0 1 1 0 0 1
P= 1 0 0 P is found in T at i= 1 & 6
Naive Algorithm Complexity
• This for loop from 3 to 5 executes for n-m + 1(we need at least m
characters at the end) times and in iteration we are doing m
comparisons. So the total complexity is O (n-m+1).
P, NP, NP-Complete, NP-Hard Problems
• A problem is said to be Polynomial Problem (P) if it can be solved in
polynomial time using deterministic algorithm, like O(nk), where K is
constant.
• Example; linear search, binary search, insertion sort, merge sort
• Polynomial problems can be solve and verify in polynomial time
• The problems that can not be solved in Polynomial time are called NP
hard problems
• Example; subset sum problem
i. Approximation
ii. Randomization
iii. Parameterization
iv. Heuristic