DAA-PPT
DAA-PPT
Syllabus
Module-2
Divide and Conquer: General method, Recurrence equation for divide and conquer, solving it using
Master’s theorem. , Divide and Conquer algorithms and complexity Analysis of Finding the maximum &
minimum, Binary search, Merge sort, Quick sort.
Decrease and Conquer Approach: Introduction, Insertion sort, Graph searching algorithms,
Topological Sorting. It’s efficiency analysis.
Textbook 2: Chapter 3(Sections 3.1,3.3,3.4,3.5,3.6)
Textbook 1: Chapter 4 (Sections 4.1,4.2,4.3), Chapter 5(Section 5.1,5.2,5.3)
Module-3
Greedy Method: General method, Coin Change Problem, Knapsack Problem, solving Job sequencing
with deadlines Problems.
Minimum cost spanning trees: Prim’s Algorithm, Kruskal’s Algorithm with performance analysis.
Single source shortest paths: Dijkstra's Algorithm. Optimal Tree problem: Huffman Trees and
Codes.
Transform and Conquer Approach: Introduction, Heaps and Heap Sort.
Textbook 2: Chapter 4(Sections 4.1,4.3,4.5)
Module-4
Dynamic Programming: General method with Examples, Multistage Graphs.
Transitive Closure: Warshall’s Algorithm. All Pairs Shortest Paths: Floyd's Algorithm, Knapsack
problem, Bellman-Ford Algorithm, Travelling Sales Person problem.
Space-Time Tradeoffs: Introduction, Sorting by Counting, Input Enhancement in String Matching
Harspool’s algorithm.
Textbook 2: Chapter 5 (Sections 5.1,5.2,5.4,5.9)
Textbook 1: Chapter 8(Sections 8.2,8.4), Chapter 7 (Sections 7.1,7.2)
Module-5
Backtracking: General method, solution using back tracking to N-Queens problem, Sum of subsets
problem, Graph coloring, Hamiltonian cycles Problems.
Branch and Bound: Assignment Problem, Travelling Sales Person problem, 0/1 Knapsack problem
NP-Complete and NP-Hard problems: Basic concepts, non- deterministic algorithms, P, NP, NP
Complete, and NP-Hard classes.
Textbook 1: Chapter 12 (Sections 12.1,12.2) Chapter 11(11.3)
Textbook 2: Chapter 7 (Sections 7.1,7.2,7.3,7.4,7.5) Chapter 11 (Section 11.1)
Course outcome (Course Skill Set)
At the end of the course the student will be able to:
CO 1. Analyze the performance of the algorithms, state the efficiency using asymptotic
notations and analyze mathematically the complexity of the algorithm.
CO 2. Apply divide and conquer approaches and decrease and conquer approaches in
solving the problems analyze the same
CO 3. Apply the appropriate algorithmic design technique like greedy method, transform
and conquer approaches and compare the efficiency of algorithms to solve the given
problem.
CO 4. Apply and analyze dynamic programming approaches to solve some problems. and
improve an algorithm time efficiency by sacrificing space.
CO 5. Apply and analyze backtracking, branch and bound methods and to describe P, NP and
NP Complete problems.
4. Finiteness: If we trace out the instructions of an algorithm, then for all cases, the algorithm
terminates after a finite number of steps.
5. Effectiveness: Every instruction must be very basic so that it can be carried out, in principle,
by a person using only pencil and paper. It is not enough that each operation be definite as in
criterion3; it also must be feasible
Notion / Flow /Understanding of Algorithm
•The non ambiguity requirement for each step of an algorithm cannot be
compromised.
• The range of inputs for which an algorithm works has to be specified carefully
•.The same algorithm can be represented in several different ways.
• There may exist several algorithms for solving the same problem.
Fundamentals of Algorithmic Problem Solving
Understanding the Problem
A good design of algorithm needs proper understanding of problem
If an existing algorithm is applicable select it to solve the problem
Discuss with peers to clarify all doubts regarding the problem in hand.
Clearly understand the input details (instance) required as input
Ascertaining the Capabilities of the Computational Device
To analyze an algorithm, we always need a model of computation.
Sequential model
(Object oriented)
Parallel model
Quantum Model
Basically choosing computational model is more relevant when solving complex
problems
Choosing between Exact and Approximate Problem Solving
Solving the problem exactly or solving it approximately. In the former case, an
algorithm is called an exact algorithm; in the latter case, an algorithm is called
an approximation algorithm.
Few problems cannot have exact solution such as extracting square roots,
solving nonlinear equations, and evaluating definite integrals.
Many a times find exact solution may slower execution speed, Some
approximation algorithm solves sophisticated problem exactly
Algorithm Design Technique
A general approach to solving problems algorithmically that is applicable to a
variety of problems from different areas of computing
Design techniques includes understanding analyzing exiting algorithms,
These will act as guide to solve new problem
Algorithm design is a creative art, needs creative thinking and practice
Techniques allows us to classify the algorithm
Computing the number of times the basic operation is executed is easy. The
total running time is determined by basic operations count
Orders of Growth, Break Even Point
A difference in running times on small inputs is not what really distinguishes
efficient algorithms from inefficient ones.
For example, the greatest common divisor of two small numbers, it is not
immediately clear how much more efficient Euclid’s algorithm is compared to the
other algorithms, the difference in algorithm efficiencies becomes clear for larger
numbers only.
For large values of n, it is the function’s order of growth that counts which contains
values of a few functions particularly important for analysis of algorithms
600
500
400
n^2
300
200 n^3
100
0
1 2 4 8
n n2 n3
1 1 1
2 4 8
4 16 64
8 64 512
16 256 4096
100 10000 1000000
1000 1000000 1000000000
250000
200000
150000
20
40
100000
60
50000
0
n logn n2 n3
Break Even Point
8000
7000
6000
5000
4000 3x^2+2
3000 3x
2000
1000
0
2 4 6 10 15 20 25 50
N O B O D Y N O T I C E H I M T
N O T P
N O T
N O T
N O T
N O T
N O T
N O T
Divide-and-Conquer
1.A problem is divided into several sub problems of the same type, ideally of
about equal size.
2. The sub problems are solved (typically recursively, though sometimes a different
algorithm is employed, especially when sub problems become small enough).
3. If necessary, the solutions to the sub problems are combined to get a solution
to the original problem.
Example Sum of n values
a1+a2+a3+a4+……..an
=(a1+a2+…….+an/2) +( an/2+1+….an)
We can divide list till the size of the problem is small enough to solve trivially
Ex:
t(n)=2t(n/2)+1
Here a=2 b=2 f(n)->n^d
F(n)=1 Hence d=0
a>b^d Hence t(n)=O(n^log 2 2)=O(n)
t(n)=t(n/2)+1
a=1 b=2 f(n)->n^d Hence d=0
a==b^d Hence t(n)=O(n^d log 2 n)=O((n^0 log 2 n)=log 2 n
Algorithm BinSearch (a,n,x)
// Given an array a[l:n] of elements in non decreasing
// order,n > 0,determine whether x is present, and
// if so ,return j such that x = a[j]; else return 0.
{
low :=1;high :=n;
while (low<=high) do
{
mid:=[(low+high)/2;
if (x <a[mid]) then
high :=mid-1;
else
If (a>a[mid]) then
low :=mid+ 1;
else
return mid;
}
return 0;
}
Algorithm BinSearch (a,i,l,x)
// Given an array a[l:n] of elements in non decreasing
// order,n > 0,determine whether x is present, and
// if so ,return j such that x = a[j]; else return 0.
{
if(i==l) then // If Small(P)
{
If (x = a[ i ]) then
return i;
else
return 0;
else
{
// Reduce P into a smaller sub problem.
mid:=(i+l)/2;
if (x = a[mid]) then
return mid;
else
if (x < a[mid]) then
return BinSrch (a,i,mid-1,x);
else
return BinSrch (a, mid +1,l x );
}
}
Algorithm MaxMin(a, j, max, min)
// a[i:n] is a global array. Parameters i and j are integers, 1<=i<=j<=n.
// The effect is to set max and min to the largest and smallest values in a(I,j)
{
if (i = j) then
max:=min:=a[i]; // Small(P)
else
if (i = =j)then // Another case of Small(P)
if (a[i]<a[j]) then
max :=a[j]; min=a[ i ];
else
max:=a[i]; min:=a[j];
else
{ //n is not small, divide P into sub problems determine value of mid .
mid:=(i + j)/2
// Solve the sub problems.
MaxMin(i,mid,max,min);
MaxMin(mid+i,j,maxi,mini);
// Combine the solutions.
if (max<maxi) then max:=maxi;
if (min >mini)then min:=mini; }
1 2 3 4 5 6 7 8 9 10 Mid
179 285 310 351 652 254 423 861 450 520 (low +
high)/2
179 285 310 351 652 254 423 861 450 520 5
179 285 310 351 652 3
179 285 310 351 652 2
179 285 310 1
1,1,2
Merge(low, mid, high) Merge(1,1,2)
179 285
1,1,2 Merge(1,1,2)
h :=low; i=low; j :=mid+ 1; if (h >mid) then H=1 i=1 j=2
while ((h < mid) and (j < high)) do for k :=j to high do
{ {
if (a[ h ] <a[ j ] )then b[i]:=a[k];
{ i :=i + 1;
b[ I ] :=a[ h] ; }
h :=h + 1; else
} for k :=h to mid do
Else {
{ b[i] :=a[k];
b[ I ] -=a[ j ] ; i :=i + 1;
j :=j+ l; }
} for k :=low to high do
i:=i + 1; a[k] :=b[k];
}
//b[ ] is an auxiliary array
QUICK SORT (C.A. R.Hoare )
•Quick sort use divide and conquer approach such that no merging and use of
auxiliary array is required ( An example of In place sorting and external sorting)
• It performs sorting by selecting during each iteration one element called pivot
element
• The pivot element is placed such that all elements preceding this are smaller
or equal to selected element
• All elements succeeding this are greater or equal.
• The sorting is again performed on the divided list by selecting new element
• In quick sort, the division into two sub arrays is made so that the
sorted sub arrays do not need to be merged later. This is accomplished by
rearranging the elements in a[l:n] such that a[i] < a[j]for all i between1
and m and all j between m+1and n for some m, 1< m < n.
•Thus, the elements in a[l:m] and a[rn+1:n] can be independently sorted
• . If m = 1 and p = n, then a[n+1] must be defined and must be greater than or
equal to all elements in a[l:n]
DFS and BFS
Topological Sorting
Greedy method
Example:
Fill a Five KG capacity Bag with different Items for sale
Item No of packets Item weight Profit
Item 1 06 250 gram 100
Item 2 05 500 gram 050
Item 3 08 400 gram 075
Item 4 03 1000 gram 125
Any combination of item that will yield maximum profit is optimal solution
In greedy method suggests that one can devise an algorithm that works
in stages considering one input at a time
If the inclusion of the next input into the partially constructed optimal
Solution will result in an infeasible solution then this input is not added to the
partial solution. Other wise it is added.
One method generally available is to produce large set of subset and try each
one of them a subset method is applicable n! ( combinatorial problem)
Algorithm Greedy( a, n) Change Problem
{
Solution = 0 You have a set of coins / Notes
for(i=1; i<=n ; i ++)
{ 5, 10, 20, 50 ,
x=select(a);
if Feasible ( Solution, x); Decide what should be the optimal
solution= Solution U x number of change we should give when
} requested
return Solution
} Ex Give change of Rs 100
If(i=0; i<4;I++)
500 200 100 50 10
{
0 0 0 0 0 if(V >=Note[ i ])
num_notes [ i ]= V / Note [ i ];
V= V % Note { i ];
}
Return Num_notes;
2 W1 25 RC=20-18 1 P=0+25*1=
RC=2 25
3 W2 24 RC=2- 2/15=0.13 P=25+0.13*
(0.13*15) 24
P=28.12
4 W3 15 0 0 28.12
2 W2 24 RC=20-15 1 P=0+24*1=24
RC=5
3 W3 15 RC=5-(0.5*10) 5/10=0.5 P=24+0.0.5*15
P=31.5
4 W3 25 0 0 31.5
i | j -> 0 1 2 3 4 5
v
0 0 0 0 0 00 0
1 0 0 12 12 12 12
2 0 10 12 22 22 22
3 0 10 12 22 30 32
4 0 10 15 25 30 37
V(3,5)=max(v(2,5),v(2,2)+20) --1
V(2,5)=max(v(1,5),v(1,4)+10) - --2
V(1,5)=max(v(0,5),v(0,3)+12) = 12 --3
V(1,4)=max(v(0,4),v(0,2)+12)=12 --4
V(2,2)=max(v(1,2),v(1,1)+10) --5
V(1,1)=v(0,1)=0 --6
V(1,2)=max(v(0,2),v(0,1)+12=12 --7 Substitute 6,7 in 5
V(2,2)=12
V(3,5)=32 –Check result
Substitute 3 and 4 in 2
V(2,5)=max(v(1,5),v(1,4)+10)=max(12,12+10)=max(12,22)=22
V(2,5)=22-----8
V(3,3)=max(v(2,3),v(2,0)+20)
V(2,3)=max(v(1,3),v(1,2)+10) --8
V(1,3)=max(v(0,3),v(0,1)+12)=12 --9
V(1,2)=max(v(0,2),v(0,1)+12=12 --10
Substitute 6,7 in 5
v(2,3)=max(12,22)=22 -11
V(2,0)=v(1,0) =0
V(3,3)= max( v(2,3),v(2,0)+20)=22---12 Find answer for A
i | j -> 0 1 2 3 4 5
v
0 0 0 0 0 00 0
1 0 -- -- -- -- --
2 0 -- -- -- -- --
3 0 -- -- -- -- --
4 0 -- -- -- -- V(4,5)
Solve:
1 Note down results obtained in previous step
2 Once filled follow steps to determine value of Xi
3 Generate weight set
N= 4 M=5, W=(2,1,3,2) P=(12,10,20,15)
i | j -> 0 1 2 3 4 5
v
0 0 0 0 0 00 0
1 0 0 12 12 12 12
2 0 10 12 22 22 22
3 0 10 12 22 30 32
4 0 10 15 25 30 37
3. p=100
1 2
j1
1 2
j4 j1
p=100+22=122
No other jobs can be added as job slots are full {j4,j1} optimal solution
A B C D E F
A 0 3 INF INF 6 5
B 3 0 1 INF INF 4
C INF 1 0 6 INF 4
D INF INF 6 0 8 5
E 6 INF INF 8 0 2
F 5 4 4 5 2 0
single-source shortest-paths problem (Dijkstra’s algorithm )
for a given vertex called the source in a weighted connected graph, find
shortest paths to all its other vertices.
1. Dijkstra’s algorithm finds the shortest paths to a graph’s vertices in order of
their distance from a given source
2. First finds the shortest path from the source to a vertex nearest to it
among all vertex connected to source vertex
3. Let this vertex be V, when we reach V we find the next nearest vertex U among all
vertex adjacent to V
At any point smallest distance is D(V)+w(V,U) among all U adjacent V
E E E B B E D C E E
Huffman’s algorithm
Step 1 Initialize n one-node trees and label them with the symbols of the alphabet
given. Record the frequency of each symbol in its tree’s root to indicate the
tree’s weight. (More generally, the weight of a tree will be equal to the sum of
the frequencies in the tree’s leaves.)
symbol A B C D _
frequency 0.35 0.1 0.2 0.2 0.15
0.25
0.60 1.0
0.25
A B C D -
11 100 00 01 101
Total Fixed Variable
Bits length Length
=15 =12
0.35*2 + 3*0.1 + 2*.2 + 2*.2 + 3*.15= 2.25
CR=(3-2.25)/3*100=25%
BAD 1001101
1. The shape property—the binary tree is essentially complete (or simply complete),
i.e., all its levels are full except possibly the last level, where only some rightmost leaves
may be missing.
2. The parental dominance or heap property—the key in each node is greater than or
equal to the keys in its children. (This condition is considered automatically satisfied for
all leaves.)
Important Properties Of Heaps
1. There exists exactly one essentially complete binary tree with n nodes. Its
height is equal to h=log2 (n).
2. The root of a heap always contains its largest element / Smallest element
3. A node of a heap considered with all its descendants is also a heap.
4. A heap can be implemented as an array by recording its elements in the top
down, left-to-right fashion. It is convenient to store the heap’s elements in
positions 1 through n of such an array, leaving H[0] either unused or putting
there a sentinel whose value is greater than every element in the heap. In such
a representation,
a. the parental node keys will be in the first [n/ 2] positions of the array while the
leaf keys will occupy the last n/2 positions;
b. the children of a key in the array’s parental position i (1 ≤ i ≤ n/2) will be in
positions 2i and 2i + 1, and, correspondingly, the parent of a key in position i (2
≤ i ≤ n) will be in position [i/2]
2, 9, 7, 6, 5, 8.
40,80,35,90,45, 50, 70
1
3
Backward Approach with Directed graph of K number of stages
d (k-1,j)=c(j,t) if path available else infinity
d (4,7)=7 d(4,8)=3
1
Input Enhancement in String Matching
Horspool’s Algorithm
Consider, as an example, searching for the pattern BARBER in some text:
s0--------- . . . C--------------- ------------ sn
BAR BE R
Staring with letter R if all character matches we consider the pattern is matched
If a mismatch occurs, we need to shift the pattern to the right
Shift should be as large as possible
While matching the following cases can occur
Case 3: If c happens to be the last character in the pattern but there are no c’s
among its other m - 1 characters—e.g., c is letter R in our example—the
situation is similar to that of Case 1 and the pattern should be shifted by the
entire pattern’s length m:
s0 . . . MER... sn-1
LEADER
LEADER
Case 4: Finally, if c happens to be the last character in the pattern and there
are other c’s among its first m - 1 characters—e.g., c is letter R in our
example—the situation is similar to that of Case 2 and the rightmost occurrence
of c among the first m - 1 characters in the pattern should be aligned with the
text’s c:
s0 . . . AR.. . sn-1
REORDER
REORDER
We can pre compute shift sizes and store them in a table called shift table
Horspool’s algorithm
Step 1 For a given pattern of length m and the alphabet used in both the
pattern and text, construct the shift table as described above.
Step 2 Align the pattern against the beginning of the text.
Step 3 Repeat the following until either a matching substring is found or the
pattern reaches beyond the last character of the text. Starting with the last
character in the pattern, compare the corresponding characters in the pattern
and text until either all m characters are matched (then stop) or a mismatching
pair is encountered. In the latter case, retrieve the entry t(c) from the c’s column
of the shift table where c is the text’s character currently aligned against the last
character of the pattern, and shift the pattern by t(c) characters to the right
along the text
B A R B E R
4 3 2 1 0
J I M - S A W - M E - I N - B A R B E R - S H O p
B A R B E R →
1 2 3 4 B A R B E R →
1 B A R B E R →
B A R B E R →
1 2 3 B A R B E R
ALGORITHM ShiftTable(P [0..m - 1])
//Fills the shift table used by Horspool’s
//Input: Pattern P [0..m - 1] and an alphabet of
possible characters
//Output: Table[0..size - 1] indexed by the
alphabet’s characters and
// filled with shift sizes computed
for i ← 0 to size-1 do Table[ i ] ← m
for j ← 0 to m - 2 do Table[P[ j ] ] ← m - 1 - j
return Table
B A R B E R B A R B E R
0 1 2 3 4 5 4 3 2 1 0
ALGORITHM HorspoolMatching(P [0..m − 1], T [0..n − 1])
{
//Implements Horspool’s algorithm for string matching
//Input: Pattern P [0..m − 1] and text T [0..n − 1]
//Output: The index of the left end of the first matching substring
// or −1 if there are no matches
ShiftTable(P [0..m − 1])
//generate Table of shifts
i ← m − 1 //position of the pattern’s right end
while i ≤ n − 1 do
{
k ← 0 //number of matched characters
while (k ≤ m − 1 and P [m − 1 − k] = = T [i − k] ) do
{
k←k+1
if (k == m)
return ( i − m + 1 )
else
i ← i + Table[T[ i ] ]
}
}
return −1
}
ALGORITHM ComparisonCountingSort(A[0..n - 1])
//Sorts an array by comparison counting
//Input: An array A[0..n - 1] of orderable elements
//Output: Array S[0..n - 1] of A’s elements sorted in nondecreasing order
for i ← 0 to n - 1 do Count[i] ← 0;
for i ← 0 to n - 2 do
for j ← i + 1 to n - 1 do
if A[i] < A[j]
Count[j] ← Count[j] + 1
else
Count[i] ← Count[i] + 1
for i ← 0 to n - 1 do S[Count[i]] ← A[i]
return S
13 11 12 13 12 12
Array Values 11 12 13
Frequencies 1 3 2
Distribution 1 4 6
Such a matrix, called the transitive closure of the digraph, would allow us to determine in
constant time whether the j th vertex is reachable from the I th vertex
The transitive closure of a directed graph with n vertices can be defined as the n × n
boolean matrix T = {t ij}, in which the element in the I th row and the j th column is 1 if
there exists a nontrivial path (i.e., directed path of a positive length) from the I th vertex
to the j th vertex; otherwise, t ij is 0
SINGLE-SOURCE SHORTEST PATHS ( BelllmanFord Algorithm)
The Knapsack Problem and Memory Functions
1. Among the subsets that do not include the ith item, the value of an optimal
subset is, by definition, F (i - 1, j)
2. Among the subsets that do include the ith item (hence, j - wi ≥ 0), an optimal
subset is made up of this item and an optimal subset of the first i - 1 items
that fits into the knapsack of capacity j - wi. The value of such an optimal
subset is vi + F (i - 1, j - wi).
V[ i, j ]= max(v[i-1,j],v[i-1,j-wi]+pi wi <j
= v[i-1,j] wi >j
=0
P, NP, and NP-Complete Problems
If worst case time complexity of an algorithm is represented by some
polynomial ie O(p(n)). They are refereed as polynomial time algorithm
Q3 1 Halt Q2 1 Q3
Q3 0 Q2 Q2 1 Q4
Deterministic Yes / No Non-deterministic Can be
output YES or NO
Problems that can be solved in polynomial time are called tractable, and
problems that cannot be solved in polynomial time are called intractable
Program Halting Contradiction
Class NP: Class NP is the class of decision problems that can be solved by
nondeterministic polynomial algorithms. This class of problems is called
Nondeterministic polynomial. (NP class)
Problem Assign one job to each person, the total cost of the processing all job should be
minimum
Knapsack Problem
ub = v + (W - w)(Vi+1/Wi+1) To determine upper bound .(maximization)