DSAL-assignment No-7-8-9-10
DSAL-assignment No-7-8-9-10
AIM: Represent any real world graph using adjacency list /adjacency matrix find minimum
spanning tree using Kruskal‘s algorithm.
OBJECTIVE:
1. Learn the concepts of graph as a data structure and their applications in
everyday life.
2. Understand graph representation (adjacency matrix, adjacency list, adjacency
multi list)
THEORY:
1. What is a graph? Various terminologies and its applications. Explain in brief.
Definition : A graph is a triple G = (V,E, φ) where
• V is a finite set, called the vertices of G,
• E is a finite set, called the edges of G, and
• φ is a function with domain E and codomain P2(V ).
In case of labeled graphs, the labels themselves may be introduced into the entries.
AB C D
A 10 4 1
B 15
C 9
D
Kruskal’s Algorithm:
Step 1: Choose the arc of least weight.
Step 2: Choose from those arcs remaining the arc of least weight which does not
form a cycle with already chosen arcs. (If there are several such arcs, choose one
arbitrarily.)
Step 3: Repeat Step 2 until n – 1 arcs have been chosen.
INPUT:
Enter the no. of nodes in graph. Create the adjacency LIST
OUTPUT:
Display result of each operation with error checking.
Cost of
MST - 39
Cost of
MST - 37
FAQS:
1. What is graph?
2. Application of Prim‘s & Kruskal‘s algorithm.
3. What are the traversal techniques?
4. What are the graph representation techniques?
5. What is adjacency Matrix?
6. What is adjacency list?
7. What is adjacency Multi-list?
b) Prim’s Algorithm
AIM: A business house has several offices in different countries; they want to lease
Phone lines to connect them with each other and the phone company charges
different rent to connect different pairs of cities. Business house want to connect all
Its offices with a minimum total cost. Solve the problem by suggesting appropriate
data structures
OBJECTIVES:
1. To understand minimum spanning tree of a Graph
2. To understand how Prim‘s algorithm works
PROBLEM SPECIPICATIONS:
DATA STRUCTURES TO BE USED:
Array: Two dimensional array (adjacency matrix) to store the adjacent vertices & the
weights associated edges.
One dimensional array to store an indicator for each vertex whether visited or not.
#define max 20
int adj_ver[max][max];
int edge_wt[max][max];
int ind[max];
CONCEPTS TO BE USED:
Arrays
Function to construct head list & adjacency matrix for a graph.
Function to display adjacency matrix of a graph.
Function to generate minimum spanning tree for a graph using Prim‘s algorithm.
THEORY:
Spanning Tree:
A Spanning Tree of a graph G = (V, E) is a sub graph of G having all vertices of G and no
cycles in it.
Minimal Spanning Tree: The cost of a graph is the sum of the costs of the edges in the
weighted graph. A spanning tree of a graph G= (V, E) is called minimal cost spanning tree
or simply the minimal spanning tree of G if its cost is minimum.
When a graph G is connected, depth first or breadth first search starting at any
vertex visits all the vertices in G.
The edges of G are partitioned into two sets i.e. T for the tree edges & B for back
edges. T is the set of tree edges and B for back edges. T is the set of edges
used or traversed during the search & B is the set of remaining edges.
The edges of G in T form a tree which includes all the vertices of graph G and this
tree is called as spanning tree.
Definition: Any tree, which consists solely of edges in graph G and includes all the
vertices in G, is called as spanning tree. Thus for a given connected graph there are
multiple spanning trees possible. For maximal connected graph having ‗n‘ vertices the
number of different possible spanning trees is equal to n.
Cycle: If any edge from set B of graph G is introduced into the corresponding spanning
tree T of graph G then cycle is formed. This cycle consists of edge (v, w) from the set B
and all edges on the path from w to v in T.
Prim's algorithm: Prim‘s algorithm is an algorithm in graph theory that finds a minimum
spanning tree for a connected weighted graph. This means it finds a subset of the
edges that forms a tree that includes every vertex, where the total weight of all the
edges in the tree is minimized. The algorithm was discovered in 1930 by
mathematician Vojtech Jarník and later independently by computer scientist Robert C.
Prim in 1957 and rediscovered by Edsger Dijkstra in 1959. Therefore it is sometimes
called the DJP algorithm, the Jarník algorithm, or the Prim-Jarník algorithm.
An arbitrary node is chosen initially as the tree root (any node can be
considered as root node for a graph). The nodes of the graph are then
appended to the tree one at a time until all nodes of the graph are included.
The node of the graph added to the tree at each point is that node adjacent to a node of
the tree by an arc of minimum weight. The arc of minimum weight becomes a tree arc
containing the new node to tree. When all the nodes of the graph have been added to the
tree, a minimum spanning tree has been constructed for the graph.
INPUT:
Graph entered as an adjacency matrix for n vertices i.e. fill an n*n matrix with the values of
the weights of the edges of the graph where the row number and column number as the
two vertices of one edge.
OUTPUT: Display adjacency matrix for the constructed graph. Display minimum spanning
tree using Prim‘s algorithm.
Sample Input/Output:
Mumbai (2) 1 1
4 6
5 4
3 2
0
Bangalore (3) 2 2
5 5
6 8
Hyderabad (4) 1 4
2 6
5 3
5 3
7 4
0
Chennai (5) 2 4
3 5
6 8
7 7
4 3
0
Delhi (6) 3 8
5 8
7 3
0
Ahmadabad (7) 4 4
5 7
6 3
0
Total cost: 17
Testing:
Test program for following test cases
For each test case:
a) Display the total number of comparisons required to construct the graph in
computer memory.
b) Display the results as given in the sample o/p above.
c) Finally conclude on time & time space complexity for the construction of the graph
and for generation of minimum spanning tree using Prim‘s algorithm.
Time Complexity:
For the construction of an undirected graph with ‗n‘ vertices and ‗e‘ edges using
adjacency list is O (n + e), since for every vertex ‗v‘ in G we need to store all adjacent
edges to vertex v.
In Prim‘s algorithm to get minimum spanning tree from an undirected graph with
‗n‘ vertices using adjacency matrix is O(n2).
Using Kruskal‘s algorithm
using adjacency matrix = O(n2).
using adjacency list=O(eloge)
Pseudo code:
Structure to be used
typedef struct edges
{
int v1,v2,wt;
}edge;
end
end return(0);
end
end
end
CONCLUSION:
The cost of spanning tree of graph G is the sum of the costs of the edges in that tree. Any
connected graph with n vertices must have at least n-1 edges and all connected graphs
with n-1 edges are trees.
INPUT:
Enter the no. of nodes in graph. Create the adjacency LIST
OUTPUT:
Display result of each operation with error checking.
Cost of
MST - 39
Cost of
MST - 37
FAQS:
1. Explain the PRIM‘s algorithm for minimum spanning tree.
2. What are the traversal techniques?
3. What are the graph representation techniques?
8.Implementation of Dijikstra’s algorithm
AIM: Represent a given graph using adjacency matrix /adjacency list and find the
shortest path using Dijkstra's algorithm (single source all destination).
OBJECTIVE:
1. To understand the application of Dijkstra‘s algorithm
THEORY:
1. Explain in brief with examples how to find the shortest path using Dijkstra‘s
algorithm.
1. To find the shortest path between points, the weight or length of a path is calculated
as the sum of the weights of the edges in the path.
2. A path is a shortest if there is no path from x to y with lower weight.
3. Dijkstra's algorithm finds the shortest path from x to y in order of increasing distance
from x. That is, it chooses the first minimum edge, stores this value and adds the
next minimum value from the next edge it selects.
4. It starts out at one vertex and branches out by selecting certain edges that lead to
new vertices.
5. It is similar to the minimum spanning tree algorithm, in that it is "greedy", always
choosing the closest edge in hopes of an optimal solution.
Example:
It is easiest to think of the geographical distances, with the vertices being places,
such as cities.
Imagine you live in Redville, and would like to know the shortest way to get to the
surrounding towns: Greenville, Blueville, Orangeville, and Purpleville. You would be
confronted with problems like: Is it faster to go through Orangeville or Blueville to get to
Purpleville? Is it faster to take a direct route to Greenville, or to take the route that goes
through Blueville? As long as you knew the distances of roads going directly from one city
to another, Dijkstra's algorithm would be able to tell you what the best route for each of the
nearby towns would be.
Begin with the source node (city), and call this the current node. Set its value to 0. Set
the value of all other nodes to infinity. Mark all nodes as unvisited.
For each unvisited node that is adjacent to the current node (i.e. a city there is a direct
route to from the present city), do the following. If the value of the current node plus the
value of the edge is less than the value of the adjacent node, change the value of the
adjacent node to this value. Otherwise leave the value as is.
Set the current node to visited. If there are still some unvisited nodes, set the unvisited
node with the smallest value as the new current node, and go to step 2. If there are no
unvisited nodes, then we are done.
In other words, we start by figuring out the distance from our hometown to all of the towns
we have a direct route to. Then we go through each town, and see if there is a quicker
route through it to any of the towns it has a direct route to. If so, we remember this as our
current best route.
Step I:
We set Redville as our current node. We give it a value of 0, since it doesn't cost anything
to get to it from our starting point. We assign everything else a value of infinity, since we
don't yet know of a way to get to them.
Step II:
Next, we look at the unvisited cities our current node is adjacent to. This means Greenville,
Blueville and Orangeville. We check whether the value of the connecting edge, plus the
value of our current node, is less than the value of the adjacent node, and if so we change
the value. In this case, for all three of the adjacent nodes we should be changing the value,
since all of the adjacent nodes have the value infinity. We change the value to the value of
the current node (zero) plus the value of the connecting edge (10 for Greenville, 5 for
Blueville, 8 for Orangeville). We now mark Redville as visited, and set Blueville as our
current node since it has the lowest value of all unvisited nodes.
Step III:
The unvisited nodes adjacent to Blueville, our current node, are Purpleville and Greenville.
So we want to see if the value of either of those cities is less than the value of Blueville
plus the value of the connecting edge. The value of Blueville plus the value of the road to
Greenvile is 5 + 3 = 8. This is less than the current value of Greenville (10), so it is shorter
to go through Blueville to get to Greenville. We change the value of Greenville to 8,
showing we can get there with a cost of 8. For Purpleville, 5 + 7 = 12, which is less than
Purpleville‘s current value of infinity, so we change its value as well? We mark Blueville as
visited. There are now two unvisited nodes with the lowest value (both Orangeville and
Greenville have value 8). We can arbitrarily choose Greenville to be our next current node.
However, there are no unvisited nodes adjacent to Greenville! We can mark it as visited
without making any other changes, and make Orangeville our next current node.
Step IV:
There is only one unvisited node adjacent to Orangeville. If we check the values,
Orangeville plus the connecting road is 8 + 2 = 10, Purpleville's value is 12, and so we
change Purpleville's value to 10. We mark Orangeville as visited, and Purpleville is our last
unvisited node, so we make it our current node. There are no unvisited nodes adjacent to
Purpleville, so we're done!
All above steps can be simply put in a tabular form like this:
ALGORITHM:
INPUT:
The graph in the form of edges, nodes and corresponding weights, the source node
and destination node.
OUTPUT:
The shortest path and length of the shortest path
FAQs:
1. What is shortest path?
2. What are the graph representation techniques?
3. What is adjacency Matrix?
4. What is adjacency list?
5. What is adjacency Multi-list?
9. Implement Heap sort to sort given set of values using max or
min heap.
AIM: Implement Heap sort to sort a given set of values using max or min heap.
OBJECTIVE:
To understand the concept of a Heap.
THEORY:
a)Concept
i)Heap Tree
Heap is a binary tree structure with the following properties:
1.The tree is complete or almost complete
2.The key value of each node is greater than or equal to the key value of its
descendants.
ii)Max-Heap
If the key value of each node is greater than or equal to the key value of its
descendants, this heap structure is called Max-Heap.
iii)Min-Heap
If the key value of each node is less than or equal to the key value of its descendants,
this heap structure is called Min-Heap.
b)Maintenance Operations on Heap
To perform insert and delete a node in heap
structure, it needs two basic algorithms :
1.Reheap up
This operation reorders a “broken” heap by floating the last element up the tree until
it is at its correct position in the heap.
2.Reheap down
This operation reorders a “broken” heap by pushing the root down the tree until it is
at its correct position in the heap.
2.Heap Implementation
Heap implementation is possible using an array because it must be a complete or almost
complete binary tree, which allows a fixed relationship between each node and its children
and it can be calculated as :
i. For node located at ith index, its children are :
Left child : 2i + 1
Right child : 2i + 2
ii. Parent of node located at ith index : (i-1)/2
iii. Given the index for a left child, j,its right sibling at : j+1
iv. Given the index for a right child, k, its left sibling at :k-1
3.Heap ADT
4.Applications of Heap
i. Selection algorithm
ii. Priority Queue
iii. Sorting (Heap Sort)
5.Heap Sort Complexity
The Heap sort efficiency is O(n log n)
ALGORITHM:
A. Heapify_asc(data,i)
Step 1 : Set Lt = Left(i)
Step 2 : Set Rt = Right(i)
Step 3 : if Lt <= heap_size[data] - 1 and data[Lt] >
data[i]
then Set Max = Lt;
else
Set Max = i
Step 4 : if Rt <= heap_size[data] - 1 and data[Rt] >
data[Max]
then Set Max = Rt
Step 5 : if Max != i
then Swap(data[i], data[Max])
Step 6 : Heapify(data, Max)
B. BuildHeap(data)
Step 1 : Set heap_size[data] = length[data]
Step 2 : for i= (length[data]-1)/2 to 0
Heapify(data,i)
C. Heapsort(data)
Step 1 : BuildHeap(data)
Step 2 : for i = length[data] - 1 to 1
Swap(data[0],data[i])
Set heap_size[data] = heap_size[data] - 1
Heapify(data,0)
INPUT:
45, 78, 24, 36, 12
10, 28, 56, 68, 75
89, 70, 64, 52,
OUTPUT:
1. Ascending order
2. Descending order
3. Exit
Enter your choice :1
size = 5 78 45 36 24 12
After building the heap…
Sorted Elements are: 12 24 36 45 78
1. Ascending order
2. Descending order
3. Exit
Enter your choice :2
size = 5 12 24 36 45 78
After building the heap...
Sorted Elements are: 78 45 36 24 12
1. Ascending order
2. Descending order
3. Exit
Enter your choice :3
FAQS:
Assignment No. 10
Title: File Handling
Aim: To implement program for Sequential Access File
Detailed Problem Statement:
Department maintains student’s database. The file contains roll number, name, division
and address. Write a program to create a sequential file to store and maintain student
data. It should allow the user to add, delete information of student. Display information
of particular student. If record of student does not exist an appropriate message is
displayed. If student record is found it should display the student details.
Objective:
To learn Sequential file organization.
Outcome:
1. Analyse algorithms and to determine algorithm correctness.
2. Design algorithms based on techniques like brute -force, divide and conquer,
greedy, etc.).
3. Analyse of algorithms with respect to time and space complexity.
4. Able to learn Sequential File Organization.
Theory
● In order to store data permanently, secondary storage devices like hard disks,
pen drives are used. A file(stream) is a collection of related data stored in a
particular area on the secondary storage devices like hard disk.
File system
Disk
CPU
Keyboard Monitor
RAM
ADT :
1. 2. 3.
struct student struct DoB class seqfile
{ { {
Int stud_rollno; int stud_day; student stud_rec;
char stud_name[30]; int stud_month; ostream outfile;
char stud_division; int stud_year; istream infile;
char stud_address[30]; }
DoB stud_DoB; public:
float stud_percent; void create();
char stud_grade; void display(key);
} void add();
void
search(key);
Void modify(key);
void delete(key);
}
Pseudo codes:
Note : StudentData is file a name
1. Create a file
BEGIN CreateAFile
Open StudentData for output
Close StudentData
END CreateAFile
2. Display a file
BEGIN DisplayFileContents
Open StudentData for input
IF FileNotPresent
Display error message
Exit
END IF
3. Add a record
BEGIN AddNewRecords
Open StudentData for append // file pointer will automatically moved to the end of
file
IF FileNotPresent
Display error message
Exit
END IF
Close StudentData
END AddNewRecords
4. Search a record
BEGIN SearchRecord(key)
Open StudentData for input
IF FileNotPresent
Display error message
Exit
END IF
5. Modify a Record
BEGIN ModifyRecord(key)
Open StudentData for input
IF FileNotPresent
Display error message
Exit
END IF
Open Temporary file for output
WHILE Not EndofFile StudentData
Read Student Information from StudentData
IF StudentRecord contains key //key should be unique as ‘roll no’
Display Student Information
Get new information for modification
Write information into Temporary file
ELSE
Write information into Temporary file
ENDIF
END WHILE
Delete StudentData
Rename Temporary File as StudentData
Close StudentData
END ModifyRecord
6. Delete a Record
BEGIN ModifyRecord(key)
Open StudentData for input
IF FileNotPresent
Display error message
Exit
END IF
Open Temporary file for output
WHILE Not EndofFile StudentData
Read Student Information from StudentData
IF StudentRecord contains key //key should be unique as ‘roll no’
Continue // read next record
ELSE
Write information into Temporary file
ENDIF
END WHILE
Delete StudentData
Rename Temporary File as StudentData
Close StudentData
END ModifyRecord
Test Cases:
1. Open a file in reading mode which does not exist.
2. Open a file in writing mode which is already exist.
3. Search /Modify/Delete record with no key present.
4. Not able to open a new file.
5. We may have invalid file name.
Conclusion : All file handling functions are implemented for sequential file
organization and the results generated as per requirements.
FAQs: