Assignment: Course Title: Computer Algorithm Course Code: CSE 1001
Assignment: Course Title: Computer Algorithm Course Code: CSE 1001
Submitted To
Ratna Mudi
Lecturer, Department of CSE.
World University of Bang
Submitted By
Masudur Rahman
Roll - 2209
Batch - 38(A)
Dept : CSE
[School]
[Course title]
Ans to the qus. no.(01)
Algorithm: . An algorithm is a well-defined procedure that allows a computer to solve a
problem. Another way to describe an algorithm is a sequence of unambiguous instructions.
linear space complexity : If the amount of space required by an algorithm is increased with
the increase of input value, then that space complexity is said to be Linear Space Complexity.
Calculating space complexity : For calculating the space complexity, we need to know the
value of memory used by different type of datatype variables, which generally varies for
different operating systems, but the method for calculating the space complexity remains the
same.
Ex..
{
int z = a+b+c;
return(z);
}
In the above expression, variables a, b and c are all integer types, hence they will take up 4
bytes each, so total memory requirement will be (4(4) + 4) = 20 bytes, this additional 4 bytes is
for return value. And because this space requirement is fixed for the above example, hence it is
called Constant Space Complexity.
int sum( int a[ ], int n)
int x = 0;
x = x+a[i];
Return 0;
}
In the above code, 4*n bytes of space is required for the array a[ ] elements.
4 bytes each for x, n, i and the return value.
Hence the total memory requirement will be (4n + 12) , which is increasing linearly with the
increase in the input value n, hence it is called as Linear Space Complexity.
Let us understand prefix codes with a counter example. Let there be four characters a, b, c and
d, and their corresponding variable length codes be 00, 01, 0 and 1. This coding leads to
ambiguity because code assigned to c is the prefix of codes assigned to a and b. If the
compressed bit stream is 0001, the de-compressed output may be “cccd” or “ccb” or “acd” or
“ab”.
See this for applications of Huffman Coding.
There are mainly two major parts in Huffman Coding
1) Build a Huffman Tree from input characters.
2) Traverse the Huffman Tree and assign codes to characters
character Frequency
a 5
b 9
c 12
d 13
e 16
f 45
Step 1. Build a min heap that contains 6 nodes where each node represents root of a tree with
single node.
Step 2 Extract two minimum frequency nodes from min heap. Add a new internal node with
frequency 5 + 9 = 14.
Now min heap contains 5 nodes where 4 nodes are roots of trees with single element each, and
one heap node is root of tree with 3 elements
character Frequency
c 12
d 13
Internal Node 14
e 16
f 45
Step 3: Extract two minimum frequency nodes from heap. Add a new internal node with
frequency 12 + 13 = 25
Now min heap contains 4 nodes where 2 nodes are roots of trees with single element each, and
two heap nodes are root of tree with more than one nodes.
character Frequency
Internal Node 14
e 16
Internal Node 25
f 45
Step 4: Extract two minimum frequency nodes. Add a new internal node with frequency 14 + 16
= 30
character Frequency
Internal Node 25
Internal Node 30
f 45
Step 5: Extract two minimum frequency nodes. Add a new internal node with frequency 25 + 30
= 55
character Frequency
f 45
Internal Node 55
Step 6: Extract two minimum frequency nodes. Add a new internal node with frequency 45 + 55
= 100
Now min heap contains only one node.
character Frequency
Internal Node 100
Since the heap contains only one node, the algorithm stops here.
character code-word
f 0
c 100
d 101
a 1100
b 1101
e 111
Ans to the qus. no. (03)
Spanning tree : Spanning tree can be defined as a sub-graph of connected, undirected graph G that
is a tree produced by removing the desired number of edges from a graph. In other words, Spanning
tree is a non-cyclic sub-graph of a connected and undirected graph G that connects all the vertices
together. A graph G can have multiple spanning trees.
Minimum spanning tree : A minimum spanning tree is a spanning tree which has minimal
total weight. In other words, minimum spanning tree is the one which contains the least weight
among all other spanning tree of some particular graph.
Minimum spanning tree_algorithm : There are two algorithms which are being used for
this purpose.
1.Prim’s Algorithm
2.Kruskal’s Algorithm
1.Prim’s Algorithm:
Prim's Algorithm is used to find the minimum spanning tree from a graph. Prim's algorithm
finds the subset of edges that includes every vertex of the graph such that the sum of the
weights of the edges can be minimized.
Algorithm
Step 1: Select a starting vertex
Example
Construct a minimum spanning tree of the graph given in the following figure by using prim's
algorithm.
Solution
o Step 1 : Choose a starting vertex B.
o Step 2: Add the vertices that are adjacent to A. the edges that connecting the vertices
are shown by dotted lines.
o Step 3: Choose the edge with the minimum weight among all. i.e. BD and add it to MST.
Add the adjacent vertices of D i.e. C and E.
o Step 3: Choose the edge with the minimum weight among all. In this case, the edges DE
and CD are such edges. Add them to MST and explore the adjacent of C i.e. E and A.
o Step 4: Choose the edge with the minimum weight i.e. CA. We can't choose CE as it
would cause cycle in the graph.
The graph produces in the step 4 is the minimum spanning tree of the graph shown in the
above figure.
cost(MST) = 4 + 2 + 1 + 3 = 10 units.
2.Kruskal’s Algorithm :
Kruskal's Algorithm is used to find the minimum spanning tree for a connected weighted graph.
The main target of the algorithm is to find the subset of edges by using which, we can traverse
every vertex of the graph. Kruskal's algorithm follows greedy approach which finds an optimum
solution at every stage instead of focusing on a global optimum.
Algorithm
o Step 1: Create a forest in such a way that each graph is a separate tree.
o Step 2: Create a priority queue Q that contains all the edges of the graph.
o Step 3: Repeat Steps 4 and 5 while Q is NOT EMPTY
o Step 4: Remove an edge from Q
o Step 5: IF the edge obtained in Step 4 connects two different trees, then Add it to the
forest (for combining two trees into one tree).
ELSE
Discard the edge
o Step 6: END
Example
Solution
the weight of the edges given as :
Edge AE AD AC AB BC CD
Weight 5 10 7 1 3 4
Edge AB DE BC CD AE AC
Weight 1 2 3 4 5 7
The next step is to add AE, but we can't add that as it will cause a cycle.
The next edge to be added is AC, but it can't be added as it will cause a cycle.
The next edge to be added is AD, but it can't be added as it will contain a cycle.
Hence, the final MST is the one which is shown in the step 4.
the cost of MST = 1 + 2 + 3 + 4 = 10.
Algorithm Steps :
1. Find the points with minimum and maximum x coordinates. These will always be part of
the convex hull.
2. The line formed by these points divide the remaining points into two subsets, which will
be processed recursively.
3. Determine the point, on one side of the line, with the maximum distance from the line.
This point will also be part of the convex hull. The two points found before along with
this one form a triangle.
4. The points lying inside of that triangle cannot be part of the convex hull and can
therefore be ignored in the next steps.
5. Repeat the previous two steps on the two lines formed by the triangle (not the initial
line).
6. Stop when no more points are left.
Examples :
Steps 1-2: Divide points in two subsets
Steps 3-5: Find maximal distance point, ignore points inside triangle and repeat it
Graham Scan : Graham's Scan Algorithm is an efficient algorithm for finding the convex hull
of a finite set of points in the plane with time complexity O(N log N). The algorithm finds all
vertices of the convex hull ordered along its boundary. It uses a stack to detect and remove
concavities in the boundary efficiently.
Algorithm Steps :
1. Find the bottom-most point by comparing y coordinate of all points. If there are two
points with same y value, then the point with smaller x coordinate value is considered. Let the
bottom-most point be P0. Put P0 at first position in output hull.
2. Consider the remaining n-1 points and sort them by polor angle in counterclockwise
order around points[0]. If polor angle of two points is same, then put the nearest point first.
3 After sorting, check if two or more points have same angle. If two more points have same
angle, then remove all same angle points except the point farthest from P0. Let the size of new
array be m.
Phase 1 (Sort points): We first find the bottom-most point. The idea is to pre-process points be
sorting them with respect to the bottom-most point. Once the points are sorted, they form a
simple closed path (See following diagram).
What should be the sorting criteria? computation of actual angles would be inefficient since
trigonometric functions are not simple to evaluate. The idea is to use the orientation to
compare angles without actually computing them (See the compare() function below)
Phase 2 (Accept or Reject Points): Once we have the closed path, the next step is to traverse
the path and remove concave points on this path. How to decide which point to remove and
which to keep? Again, orientation helps here. The first two points in sorted array are always
part of Convex Hull. For remaining points, we keep track of recent three points, and find the
angle formed by them. Let the three points be prev(p), curr(c) and next(n). If orientation of
these points (considering them in same order) is not counterclockwise, we discard c, otherwise
we keep it. Following diagram shows step by step process of this phase
Ans to the qus. no. (05)
Floyd-Warshall Algorithm : Floyd-Warshall Algorithm is an algorithm for finding the
shortest path between all the pairs of vertices in a weighted graph. This algorithm works for
both the directed and undirected weighted graphs. But, it does not work for the graphs with
negative cycles.
Follow the steps below to find the shortest path between all the pairs of vertices.
1. Create a matrix A1 of dimension n*n where n is the number of vertices. The row and the
column are indexed as i and j respectively. i and j are the vertices of the graph.
Each cell A[i][j] is filled with the distance from the ith vertex to the jth vertex. If there is
no path from ith vertex to jth vertex, the cell is left as infinity.
2. Now, create a matrix A1 using matrix A0 . The elements in the first column and the first
row are left as they are. The remaining cells are filled in the following way.
Let k be the intermediate vertex in the shortest path from source to destination. In this
step, k is the first vertex.A[i][j] is filled with (A[i][k] + A[k][j]) if (A[i][j] > A[i][k] + A[k][j]).
That is, if the direct distance from the source to the destination is greater than the path
through the vertex k, then the cell is filled with A[i][k] + A[k][j].
In this step, k is vertex 1. We cacluate the distance from source vertex to destination
vertex through this vertex k.
For example: For A1[2, 4], the direct distance from vertex 2 to 4 is 4 and the sum of the
distance from vertex 2 to 4 through vertex (ie. from vertex 2 to 1 and from vertex 1 to 4)
is 7. Since 4 < 7, A0[2, 4] is filled with 4.
3. In a similar way, A2 is created using A3 . The elements in the second column and the
second row are left as they are.
In this step, k is the second vertex (i.e. vertex 2). The remaining steps are the same as
in step 2.
4. Similarly, A3 and A4 is also created.
In the traveling salesman Problem, a salesman must visits n cities. We can say that salesman
wishes to make a tour or Hamiltonian cycle, visiting each city exactly once and finishing at the
city he starts from. There is a non-negative cost c (i, j) to travel from the city i to city j. The goal
is to find a tour of minimum cost. We assume that every two cities are connected. Such
problems are called Traveling-salesman problem (TSP).
We can model the cities as a complete graph of n vertices, where each vertex represents a city.
If we assume the cost function c satisfies the triangle inequality, then we can use the following
approximate algorithm.
Triangle inequality
1. Approx-TSP (G= (V, E))
2. {
3. 1. Compute a MST T of G;
4. 2. Select any vertex r is the root of the tree;
5. 3. Let L be the list of vertices visited in a preorder tree walk of T;
6. 4. Return the Hamiltonian cycle H that visits the vertices in the order L;
7. }
Traveling-salesman Problem
Intuitively, Approx-TSP first makes a full walk of MST T, which visits each edge exactly two
times. To create a Hamiltonian cycle from the full walk, it bypasses some vertices (which
corresponds to making a shortcut)