Final Lab Manual
Final Lab Manual
Pune- 48
DEPARTMENTOF
COMPUTER
ENGINEERING
LAB MANUAL
PRACTICAL- DATA STRUCTURES AND ALGORITHMS LAB (210256)
Prepared by
Prof. Mrs. S. R.Dhotre
Mission
“Holistic development of students and teachers is what we
believe in and work for. We strive to achieve this by imbibing
a unique value system, transparent work culture, excellent
academic and physical environment conducive to learning,
creativity and technology transfer. Our mandate is to
generate, preserve and share knowledge for developing a
vibrantsociety.”
Department of Computer Engineering
Vision
Mission
“We believe in developing value based system for student and
staff by providing healthy and transparent work culture to
cultivate new ideas in the field of engineering and technology
which will contribute to build a vibrant Society.”
Programme Outcomes (POs)
PO1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and
an engineering specialization to the solution of complex engineering problems.
PO2. Problem analysis: Identify, formulate, research literature, and analyze complex engineering problems
reaching substantiated conclusions using first principles of mathematics, natural sciences, and engineering
sciences.
PO3. Design/development of solutions: Design solutions for complex engineering problems and design system
components or processes that meet the specified needs with appropriate consideration for the public health and
safety, and the cultural, societal, and environmental considerations.
PO4. Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to provide
valid conclusions.
PO5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering
and IT tools including prediction and modelling to complex engineering activities with an understanding of the
limitations.
PO6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
PO7. Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable development.
PO8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of
the engineering practice.
PO9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
PO10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and design
documentation, make effective presentations, and give and receive clear instructions.
PO11. Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.
PO12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
Program Specific Outcomes (PSOs)
PSO1: Project Development: Successfully complete hardware and/or software related system or application
projects, using the phases of project development life cycle to meet the requirements of service and product
industries; government projects; and automate other engineering stream projects.
PSO2: Domain Expertise: Demonstrate effective application of knowledge gained from different computer
domains like, data structures, data bases, operating systems, computer networks, security, parallel
programming, in project development, research and higher education.
PSO3: Career Development: Achieve successful Career and Entrepreneurship- The ability to employ modern computer
languages, environments, and platforms in creating innovative career paths to be an entrepreneur, and a zest for higher studies.
1. Graduate Attributes and Program Outcomes
COURSE OBJECTIVES:
COURSE OUTCOMES:
Learning Objectives:
Learning Outcome :
Learn python language.
Understand & implement concept of hash table.
Theory:
Hashing :
Hashing is the process of indexing and retrieving elements in a data structure to
provide faster way of finding the element using hash key.
OR
Hash Table :
Hash table is a data structure used for storing and retrieving data quickly. It stores data
is in an array format , where each data value has its own unique index. That’s why access
become quick if we know the index of the desired data.
Hash table uses array as an storage medium and every entry in the hash table is made
using Hash function.
Eg.,
Insert the keys = {46, 30, 33, 24, 28} in the hash table having the size of 5.
Hash table
H(46) = 46 % 5 = 1
0 30
H(30) = 30 % 5 = 0
1 46
H(33) = 33 % 5 = 3
2 28
H(24) = 24 % 5 = 4
3 33
4 24 H(28) = 28 % 5 = 3
Here, Bucket is not empty. So collision occurs . Therefore insert
The key at next empty bucket i.e. at index 2 .
Basic Operations
Hash Method:
Define a hashing method to compute the hash code of the key of the data item.
def hashFunction(self,element):
return element % self.size
Search Operation :
Example :-
def search(self, record):
found = False
position = self.hashFunction(record.get_number())
self.comparisons += 1
if(self.table[position] != None):
if(self.table[position].get_name() == record.get_name() and
self.table[position].get_number() == record.get_number()):
isFound = True
return position
isFound = True
i = self.comparisons + 1
return position
else:
print("Record not found")
return False
position += 1
if position >= self.size-1:
position = 0
self.comparisons += 1
Insert Operation :
Whenever an element is to be inserted, compute the hash code of the key
passed and locate the index using that hash code as an index in the array. Use
linear probing for empty location, if an element is found at the computed hash code.
Example :
def insert(self, record):
# checking if the table is full
if self.isFull():
print("Hash Table Full")
return False
isStored = False
position = self.hashFunction(record.get_number())
if self.table[position] == None:
self.table[position] = record
print("Phone number of " + record.get_name() + " is at position " + str(position))
isStored = True
self.elementCount += 1
# collision occured hence we do linear probing
else:
print("Collision has occured for " + record.get_name() + "'s phone number at position "
+ str(position) + " finding new Position.")
self.table[position] = record
isStored = True
self.elementCount += 1
return isStored
Delete Operation :
Whenever an element is to be deleted, compute the hash code of the key passed and locate
the index using that hash code as an index in the array. Use linear probing to get the element
ahead if an element is not found at the computed hash code. When found, store a dummy item there
to keep the performance of the hash table intact.
Collision :
Collision occurs when different keys hash to the same location in the hash table.
If collisions occur then it should be handled by applying some techniques, such
techniques are called collision handling techniques.
Collision
CollisionResolution Techniques
Resolution Techniques
Linear Probing :-
When collision occurs i.e. when two records demand for the same location in
the hash table, then the collision can be solved by placing second record linearly down
whenever the empty location is found.
Eg.,
Insert keys={37, 90, 45, 22, 17, 49, 55} in the table of size 10 using linear probing.
0 90 H(37) = 37 % 10 = 7
1 H(90) = 90 % 10 = 0
2 22 H(45) = 45 % 10 = 5
3 H(22) = 22 % 10 = 2
4 H(17) = 17 % 10 = 7 Here, collision occurs. Therefore insert the key 17
5 45 at next empty location i.e. at location 8.
6 55 H(49) = 49 % 10 = 9
7 37 H(55) = 55 % 10 = 5 Here, collision occurs. Therefore insert the key 55
8 17 at next empty location i.e. at location 6.
9 49
Double Hashing : -
Double hashing is a collision resolution technique used in hash tables. It works
by using two hash functions to compute two different hash values for a given key. The first
hash function is used to compute the initial hash value, and the second hash function is used
to compute the step size for the probing sequence.
There are two important rules to be followed for the second function :
1] It must never evaluate to zero.
2] Must make sure the all cells can be probed.
Eg.,
Insert keys={37, 90, 45, 22, 17, 49, 55} in the table of size 10 using double hashing.
1] H1(37) = 37 % 10 = 7
0 90 2] H1(90) = 90 % 10 = 0
1 17 3] H1(45) = 45 % 10 = 5
2 22 4] H1(22) = 22 % 10 = 2
3
4 5] H1(17) = 17 % 10 = 7 …………….Collision occurs
5 45 H2=M-(key%M)………….M=prime number smaller than Table_size. Prime
6 55 number smaller than Table_Size 10 is 7. Hence ,M=7
7 37 H2(17) = 7-(17%7) = 4
8 [ H1(17)+H2(17) ] % 10 = 1
9 49
6] H1(49) = 49 % 10 = 9
7] H1(55) = 55 % 10 = 5 …………….Collision occurs
H2(55) = 7 - (55%7) = 1
[ H1(55)+H2(55) ] % 10 = 6
Expected Output: Menu driver output for inserting phone number, display and look up function.
e.g
Menu
Conclusion : In this way we have implemented Hash table for quick lookup using python.
Assignment -2
Title:
Implement all the functions of a dictionary (ADT) using hashing.
Data: Set of (key, value) pairs, Keys are mapped to values, Keys must be
comparable, Keys must be unique
Learning Objectives:
1. To understand Dictionary (ADT)
2. To understand concept of hashing
3. To understand concept & features like searching using hash function.
Learning Outcome:
Theory:
Dictionary ADT
Dictionary Operations
Dictionary create()
creates empty dictionary
boolean isEmpty(Dictionary d)
tells whether the dictionary d is empty
destroy(Dictionary d) destroys
dictionary d
Hash Table is a data structure which stores data in an associative manner. In a hash
table, data is stored in an array format, where each data value has its own unique index
value. Access of data becomes very fast if we know the index of the desired data.
Thus, it becomes a data structure in which insertion and search operations are very fast
irrespective of the size of the data. Hash Table uses an array as a storage medium and uses
hash technique to generate an index where an element is to be inserted or is to be located
from.
Hashing
Hashing is a technique to convert a range of key values into a range of indexes of an
array. We're going to use modulo operator to get a range of key values. Consider an
example of hash table of size 20, and the following items are to be stored. Item are in
the (key,value) format.
Example:
def search(key):
global size
hash_value = key % size
if hashtable[hash_value][0] == key:
print("KEY", key, "FOUND AT INDEX", hash_value)
else:
flag = 0
i=0
chain = hashtable[hash_value][1]
if hashtable[hash_value][0] == key:
print("KEY", key, "FOUND AT INDEX", hash_value)
chain = -1
flag = 1
break
i += 1
if flag == 0:
print("KEY NOT FOUND")
Insert Operation :
Whenever an element is to be inserted, compute the hash code of the key passed and
locate the index using that hash code as an index in the array. Use linear probing for empty
location, if an element is found at the computed hash code.
Example:
def insert(key):
global size, total
hash_value = key % size
if hashtable[hash_value][0] is None:
hashtable[hash_value][0] = key
bucket[key % size] = hash_value
else:
flag = 0
for i in range(0, size):
hash_value = (key + i) % size
if hashtable[hash_value][0] is None:
total += 1
flag = 1
if bucket[key % size] != 1:
hashtable[bucket[key % size]][1] = hash_value
bucket[key % size] = hash_value
hashtable[hash_value][0] = key
break
if flag == 0:
print("KEY", key, "NOT INSERTED AS HASH TABLE IS FULL")
Delete Operation :
Whenever an element is to be deleted, compute the hash code of the key passed and
locate the index using that hash code as an index in the array. Use linear probing to get the
element ahead if an element is not found at the computed hash code. When found, store a
dummy item there to keep the performance of the hash table intact.
Example:
def delete(key):
global size
hash_value = key % size
if hashtable[hash_value][0] == key:
hashtable[hash_value][0], hashtable[hash_value][1] = None, -1
print("KEY", key, "WAS DELETED FROM INDEX", hash_value)
else:
flag = 0
i=0
chain1 = hash_value
chain2 = hashtable[hash_value][1]
if hashtable[hash_value][0] == key:
hashtable[chain1][1] = hashtable[chain2][1]
hashtable[chain2][0], hashtable[chain2][1] = None, -1
print("KEY", key, "WAS DELETED FROM INDEX", chain2)
chain2 = -1
flag = 1
break
i += 1
while chain2 != -1:
if hashtable[chain2][0] == key:
hashtable[chain1][1] = hashtable[chain2][1]
hashtable[chain2][0], hashtable[chain2][1] = None, -chain1
print("KEY", key, "DELETED FROM INDEX", chain2)
flag = 1
break
chain1 = chain2
chain2 = hashtable[chain2][1]
if flag == 0:
print("KEY NOT FOUND")
Collision :
Collision occurs when different keys hash to the same location in the hash table.
If collisions occur then it should be handled by applying some techniques, such
techniques are called collision handling techniques.
Collision
Collision Resolution Techniques
Resolution Techniques
Example:
Keys={ 19, 34, 25, 48, 7, 14 } Table Size = 6
Construct the hash table using linear probing with chaining without replacement.
Index Keys Chain 1) H(19) = 19 % 6 = 1
0 48 -1 2) H(34) = 34 % 6 = 4
1 19 2 3) H(25) = 25 % 6 = 1 Here, collision occurs. Therefore insert
2 25 3 the key 25 at next empty location i.e. at
2 & adjust chain table.
3 7 -1
4) H(48) = 48 % 6 = 0
4 34 -1
5) H(7) = 7 % 6 = 1 Here, collision occurs. Therefore insert
5 14 -1
the key 7 at next empty location i.e. at
3 & adjust chain table.
= 12
6
= 2
Example:
Keys={ 19, 34, 25, 48, 7, 14 } Table Size = 6
Construct the hash table using linear probing with chaining without replacement.
Keys 19 34 25 48 7 14
No. of
comparisons 1 1 5 1 3 7
= 18
6
= 3
Expected Output: Create dictionary using hash table and search the elements in table.
Title:
A book consists of chapters, chapters consist of sections and sections consist of subsections.
Construct a tree and print the nodes. Find the time and space requirements of your method.
Learning Objectives:
✓ To understand concept of class
✓ To understand concept & features of object-oriented programming.
✓ To understand concept of tree data structure.
Learning Outcome:
• Define class for structures using Object Oriented features.
• Analyze tree data structure.
Theory:
Introduction to Tree:
Definition:
A tree T is a set of nodes storing elements such that the nodes have a parent-child relationship
that satisfies the following.
• If T is not empty, T has a special node called the root that has no parent.
• Each node v of T different than the root has a unique parent node w; each node with parent w is
a child of w.
Recursive definition
• T is either empty.
• or consists of a node r (the root) and a possibly empty set of trees whose roots are the children
of r.
Tree is a widely used data structure that emulates a tree structure with a set of linked
nodes. The tree graphicaly is represented most commonly as on Picture 1. The circles are the
nodes, and the edges are the links between them.
1
Trees are usually used to store and represent data in some hierarchical order. The data are stored
in the nodes, from which the tree is consisted of.
Each node in a tree has zero or more child nodes, which are one level lower in the tree
hierarchy (by convention, trees grow down, not up as they do in nature). A node that has a child is called
the child's parent node (or ancestor node, or superior). A node has at most one parent. A node that has no
children is called a leaf, and that node is of course at the bottom most level of the tree. The height of a
node is the length of the longest path to a leaf from that node. The height of the root is the height of the
tree. In other words, the "height" of tree is the "number of levels" in the tree. Or more formally, the height
of a tree is defined as follows:
The depth of a node is the length of the path to its root (i.e., its root path). Every child node is
always one level lower than his parent.
The topmost node in a tree is called the root node. Being the topmost node, the root node will
not have parents. It is the node at which operations on the tree commonly begin (although some
algorithms begin with the leaf nodes and work up ending at the root). All other nodes can be reached
from it by following edges or links. (In the formal definition, a path from a root to a node, for each
different node is always unique). In diagrams, it is typically drawn at the top.
In some trees, such as heaps, the root node has special properties.
A subtree is a portion of a tree data structure that can be viewed as a complete tree in itself. Any
node in a tree T, together with all the nodes below his height, that are reachable from the node,
comprise a subtree of T.
An internal node or inner node is any node of a tree that has child nodes and is thus not a leaf
node.
2
Important Terms
Following are the important terms with respect to tree.
• Path − Path refers to the sequence of nodes along the edges of a tree.
• Root − The node at the top of the tree is called root. There is only one root per tree and
one path from the root node to any node.
• Parent − Any node except the root node has one edge upward to a node called parent.
• Child − The node below a given node connected by its edge downward is called its child node.
• Leaf − The node which does not have any child node is called the leaf node.
• Subtree − Subtree represents the descendants of a node.
• Visiting − Visiting refers to checking the value of a node when control is on the node.
• Traversing − Traversing means passing through nodes in a specific order.
• Levels − Level of a node represents the generation of a node. If the root node is at level 0,
then its next child node is at level 1, its grand child is at level 2, and so on.
• keys − Key represents a value of a node based on which a search operation is to be
carried out for a node.
Advantages of trees
Trees are so useful and frequently used because they have some very serious advantages:
3
Expected Output: Formation of tree structure for book and its sections.
4
Assignment –4
Title:
Beginning with an empty binary search tree, Construct binary searchtree by inserting the values
in the order given. After constructing a binary tree –
i. Insert new node
ii. Find number of nodes in longest path
iii. Minimum data value found in the tree
iv. Change a tree so that the roles of the left and right pointers are swapped atevery node
v. Search a value
Learning Objective:
Learning Outcome:
✓ To implement the basic concept of Binary Search Tree to store a number in it.
✓ To perform basic Operation Insert, Delete and search, Traverse in tree in Data structure.
Theory –
Tree represents the nodes connected by edges. Binary Tree is a special data structure used for data
storage purposes. A binary tree has a special condition that each node can have a maximum of two
children. A binary tree has the benefits of both an ordered array and a linked list as search is as
quickas in a sorted array and insertion or deletion operation are as fast as in linked list.
Binary Search tree exhibits a special behavior. A node's left child must have a value less than its
parent's value and the node's right child must have a value greater than its parent value.
A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned
properties −
• The left sub-tree of a node has a key less than to its parent node's key.
• The right sub-tree of a node has a key greater than to its parent node's key.
Thus, BST divides all its sub-trees into two segments; the left sub-tree and the right sub-tree
and can be defined as –
5
Tree Node
Following Structure is used for Node creation
Struct node
{Int data ;
Struct node *leftChild;
Struct node *rightChild;
};
6
2. Search Operation:Algorithm
3. Tree Traversal
A.In order traversal algorithm
7
3. Deleting in a BST
Expected Output:
Formation of binary search tree structure with its basic Operation Insert, Delete and search, Traverse in
tree.
Conclusion: This program gives us the knowledge binary search tree data structure and its basic
operations.
8
9
Assignment -5
Title:
Convert given binary tree into threaded binary tree. Analyze time and space complexity of the
algorithm.
Learning Objective:
To understand the basic concept of Non-Linear Data Structure “threaded binary tree” and its use
in Data structure.
Learning Outcome:
To convert the Binary Tree into threaded binary tree and analyze its time and space complexity.
Theory –
Idea of Threaded Binary Tree is to make inorder traversal faster and do it without stack and
withoutrecursion.
In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a
right pointer is NULL, it is used to store inorder successor.
Inorder traversal of a Binary treeis either be done using recursion or with the use of a auxiliarystack.
struct Node
{
int data;
Node *left, *right;
bool lbit, rbit;
}
1) Single Threaded:
Where a NULL right pointer is made to point to the inorder successorFollowing diagram shows an
example Single Threaded Binary Tree. The dotted lines represent threads.
Inorder Traversal = 4 2 5 1 6 3 7
1 -999 0
1 1 0
1 3 1
1 2 1
0 4 0 0 5 0 0 6 0 0 7 0
2 ) Double Threaded:
Where both left and right NULL pointers are made to point to inorder predecessor and inorder
successor, respectively. The predecessor threads are useful for reverse inorder traversal and
postorder traversal.
The threads are also useful for fast accessing ancestors of a node.
1 -999 0
1 1 0
1 3 1
1 2 1
0 4 0 0 5 0 0 6 0 0 7 0
Conversion of Binary Tree to Threaded Binary Tree
Initialize pointers: Traverse the binary tree in-order, and for each node, if its left child is null, make it point
to the predecessor (the previous node in in-order traversal). Similarly, if the right child is null, make it point
to the successor (the next node in in-order traversal).
Threading process:While traversing in-order, if the left child of a node is null, link it to its in-order
predecessor. If the right child is null, link it to its in-order successor.
Final threading: Finally, make the left pointer of the leftmost node point to the in-order predecessor that is
dummy node, and make the right pointer of the rightmost node point to the in-order successor that is dummy
node.
● Traversing the binary tree to thread the nodes takes O(n) time, where n is the number of nodes in the tree.
● Finding the leftmost and rightmost nodes takes O(n) time in total.
● Overall, the time complexity of the algorithm is O(n).
● The space complexity primarily depends on the recursion stack during in-order traversal, which could be
O(h), where h is the height of the tree. In the worst case (for skewed trees), it could be O(n).
● Additionally, the algorithm uses a constant amount of extra space for auxiliary variables.
● Thus, the overall space complexity is O(n).
Expected Outcome:
The binary tree into threaded binary tree in one single traversal with no extra space required.
Conclusion: Able to convert the Binary Tree into threaded binary tree and analyze its time and
space complexity.
Assignment -6
Title:
There are flight paths between cities. If there is a flight
between city A and city B then
there is an edge between the cities. The cost of the edge can be the time that flight take to reach
city B from A, or the amount of fuel used for the journey. Represent this as a graph. The node
can be represented by airport name or name of the city. Use adjacency list representation of the
graph or use adjacency matrix representation of the graph. Justify the storage representation
used.
Learning Objectives:
Learning Outcome:
Define class for graph using Object Oriented
features. Analyze working of functions.
Theory:
Graphs are the most general data structure. They are also commonly used data structures.
Graph definitions:
A non-linear data structure consisting of nodes and links between nodes.
Each node is called a vertex, each link is called an edge, and each edge connects two
vertices.
An undirected graph is a finite set of vertices together with a finite set of edges. Both sets
might be empty, which is called the empty graph.
Graph Implementation:
Different kinds of graphs require different kinds of implementations, but the fundamental
concepts of all graph implementations are similar. We'll look at several representations for one
particular kind of graph: directed graphs in which loops are allowed.
Definition:
An adjacency matrix is a square grid of true/false values that represent the edges of a
graph.
If the graph contains n vertices, then the grid contains n rows and n columns.
For two vertex numbers i and j, the component at row i and column j is true if there is
an edge from vertex i to vertex j; otherwise, the component is false.
Once the adjacency matrix has been set, an application can examine locations of the matrix
to determine which edges are present and which are missing.
Representing Graphs with Edge Lists
Definition:
Expected Output: Create Adjacency matrix to represent path between various cities.
Title:
You have a business with several offices; you want to lease phone lines to connect them
up with each other; and the phone company charges different amounts of money to connect
different pairs of cities. You want a set of lines that connects all your offices with a minimum
total cost. Solve the problem by suggesting appropriate data structures.
Learning Objective:
Learning Outcome:
To implement the spanning
To find the minimum distancebetween the vertices of Graph in Data structure.
Theory
Properties of a Greedy Algorithm:
At each step, the best possible choice is taken and after that only the sub-problem is
solved.
The method of greedy algorithm starts with a top and goes down, creating greedy
choices in a series and then reduce each of the given problem to even smaller ones.
To solve the problem by a prim's algorithm, all we need is to find a spanning tree of minimum
length, where a spanning tree is a tree that connects all the vertices together and a minimum
spanning tree is a spanning tree of minimum length.
1 It grows the tree until it spans all the vertices of the graph.
2 An edge is added to the tree, at every step, that crosses a cut if its weight is the
minimum of any edge crossing the cut, connecting it to a vertex of the graph.
Algorithm:
Conclusion: Understood the concept and basic of spanning and to find the minimum distance between
thevertices of Graph in Data structure.
Assignment -8
Title:
A Dictionary stores keywords & its meaning. Provide facility for adding new keywords, deleting
keywords, updating values of any entry. Provide facility to display whole data sorted in ascending/
Descending order. Also find how many maximum comparisons may require for finding any keyword.
Use Height balance tree and find the complexity for finding a keyword.
Learning Objectives:
Learning Outcome:
Theory:
An empty tree is height balanced tree if T is a nonempty binary tree with TL and
TR asits left and right sub trees. The T is height balance if and only if Its balance factor is
0, 1, -1.
AVL (Adelson- Velskii and Landis) Tree: A balance binary search tree. The best
search time, that is O (log N) search times. An AVL tree is defined to be a well-balanced
binary search tree in which each of its nodes has the AVL property. The AVL property is
that the heights of the left and right sub-trees of a node are either equal or if they differ only
by 1.
It is observed that BST's worst-case performance is closest to linear search
algorithms, that is Ο(n). In real-time data, we cannot predict data pattern and their
frequencies. So, a need arises to balance out the existing BST.
Named after their inventor Adelson, Velski & Landis, AVL trees are height
balancing binary search tree. AVL tree checks the height of the left and the right sub-trees
and assures that the difference is not more than 1. This difference is called the Balance
Factor.
Here we see that the first tree is balanced and the next two trees are not balanced −
In the second tree, the left subtree of C has height 2 and the right subtree has height
0, so the difference is 2. In the third tree, the right subtree of A has height 2 and the left is
missing, soit is 0, and the difference is 2 again. AVL tree permits difference (balance factor)
to be only 1.
If the difference in the height of left and right sub-trees is more than 1, the tree is balanced
usingsome rotation techniques.
AVL Rotations
To balance itself, an AVL tree may perform the following four kinds of rotations −
Left rotation
Right rotation
Left-Rightrotation
Right-Leftrotation
The first two rotations are single rotations, and the next two rotations are double
rotations. To have an unbalanced tree, we at least need a tree of height 2. With this simple
tree, let's understand them one by one.
Left Rotation
If a tree becomes unbalanced, when a node is inserted into the right subtree of the
rightsubtree, then we perform a single left rotation −
In our example, node A has become unbalanced as a node is inserted in the right
subtreeof A's right subtree. We perform the left rotation by making A the left-subtree of B.
Right Rotation
AVL tree may become unbalanced, if a node is inserted in the left subtree of the
leftsubtree. The tree then needs a right rotation.
As depicted, the unbalanced node becomes the right child of its left child by performing a
rightrotation.
Left-Right Rotation
A node has been inserted into the right subtree of the left subtree.
This makes C an unbalanced node. These scenarios cause AVL tree
to perform left-right rotation.
We shall now right rotate the tree, making B the new root node
of this subtree. C now becomes the right subtree of its own left
subtree.
State Action
A node has been inserted into the left subtree of the right subtree.
This makes A, an unbalanced node with balance factor 2.
41
Algorithm AVL TREE:
Insert:-
Expected Output: Allow Add, delete operations on dictionary and also display data in sorted order.
Conclusion: This program gives us the knowledge height balanced binary tree.
Assignment -9
Title:
Implement the Heap/Shell sort algorithm implemented in Java demonstrating heap/shell data
structure with modularity of programming language .
Learning Objectives:
To understand concept of heap in data structure.
To understand concept & features of java language.
Learning Outcome:
Define class for heap using Object Oriented features.
Analyze working of heap sort .
Theory:
Heap Sort:
Let us first define a Complete Binary Tree. A complete binary tree is a binary tree in
which every level, except possibly the last, is completely filled, and all nodes are as far left
as possible (Source Wikipedia)
A Binary Heap is a Complete Binary Tree where items are stored in a special order
such that value in a parent node is greater (or smaller) than the values in its two children
nodes. The former is called as max heap and the latter is called min heap. The heap can be
represented by binary tree or array.
Why array-based representation for Binary Heap?
Since a Binary Heap is a Complete Binary Tree, it can be easily represented as array
and array based representation is space efficient. If the parent node is stored at index I, the
left child can be calculated by 2 * I + 1 and right child by 2 * I + 2 (assuming the indexing
starts at 0).
44
Heap Sort Algorithm for sorting in increasing order:
2. At this point, the largest item is stored at the root of the heap. Replace it with the last
item ofthe heap followed by reducing the size of heap by 1. Finally, heapify the root of
tree.
3. Repeat above steps until size of heap is greater than 1.
Heapify procedure can be applied to a node only if its children nodes are heapified.
Sothe heapification must be performed in the bottom up order.
The heapify procedure calls itself recursively to build heapin top-down manner.
45
Algorithm:
We will remove the largest element from the heap and put at its proper place(nth
position) in array.
After removing the largest element, which element will take its place? We will put
last element of the heap at the vacant place. After placing the last element at the root, The
new tree formed may or may not satisfy max-heap property. So, If it is not satisfying max-
heap property then first task is to make changes to the tree, So that it satisfies max-heap
property.
(Heapify process: The process of making changes to tree so that it satisfies max-heap
property is called heapify)
When tree satisfies max-heap property, again largest item is stored at the root of the
heap. We will remove the largest element from the heap and put at its proper place(n-1
position) in array. Repeat step 3 until size of array is 1 (At this point all elements are sorted.)
46
Assignment-10
Title:
Read the marks obtained by students of second year in an online examination of particular subject.
Find out maximum and minimum marks obtained in a that subject. Use heap data structure. Analyze
the algorithm.
Learning Objectives:
Learning Outcome:
Theory:
Heap is a special case of balanced binary tree data structure where the root-node
key iscompared with its children and arranged accordingly. If α has child node β then –
key(α) ≥ key(β)
As the value of parent is greater than that of child, this property generates Max Heap.
Based on this criterion, a heap can be of two types −
Min-Heap − Where the value of the root node is less than or equal to either of its children.
47
Max-Heap − Where the value of the root node is greater than or equal to either of its children.
Both trees are constructed using the same input and order of arrival.
Note − In Min Heap construction algorithm, we expect the value of the parent node to be
lessthan that of the child node.
Let's understand Max Heap construction by an animated illustration. We consider the same
inputsample that we used earlier.
INPUT:35,33,42,10,14,19,27,44,16,31
48
Step 1 − Remove root node.
Step 2 − Move the last element of last level to root.
Step 3 − Compare the value of this child node with its
parent.Step 4 − If value of parent is less than child, then
swap them. Step 5 − Repeat step 3 & 4 until Heap
property holds.
Conclusion: This program gives us the knowledge of heap and its types.
49
Assignment-11
Title:
Department maintains a student information. The file contains roll number, name, division and
address. Allow user to add, delete information of student. Display information of particular employee.
If record of student does not exist an appropriate message is displayed. If it is, then the system
displays the student details. Use sequential file to main the data.
Learning Objectives:
Learning Outcome:
Define class for sequential file using Object Oriented features.
Analyze working of various operations on sequential file.
Theory:
File organization refers to the relationship of the key of the record to the physical location
of that record in the computer file. File organization may be either physical file or a logical file.
A physical file is a physical unit, such as magnetic tape or a disk. A logical file on the other hand
is a complete set of records for a specific application or purpose. A logical file may occupy a part
of physical file or may extend over more than one physical file.
There are various methods of file organizations. These methods may be efficient for
certain types of access/selection meanwhile it will turn inefficient for other selections. Hence it is
up to the programmer to decide the best suited file organization method depending on his
requirement.
50
Sequential File Organization:
It is one of the simple methods of file organization. Here each file/records are stored one
after the other in a sequential manner. This can be achieved in two ways:
Records are stored one after the other as they are inserted into the tables. This method is called
pile file method. When a new record is inserted, it is placed at the end of the file.In the case of
any modification or deletion of record, the record will be searched in the memory blocks. Once it
is found, it will be marked for deleting and new block of recordis entered.
In the diagram above, R1, R2, R3 etc are the records. They contain all the attribute of a
row. i.e.; when we say student record, it will have his id, name, address, course, DOB etc.
Similarly R1, R2, R3 etc can be considered as one full set of attributes.
In the second method, records are sorted (either ascending or descending) each
time they are inserted into the system. This method is called sorted file method. Sorting of records
may bebased on the primary key or on any other columns. Whenever a new record is inserted, it will be
inserted at the end of the file and then it will sort – ascending or descending based on key value and
placed at the correct position. In the case of update, it will update the record and then sort thefile to
place the updated record in the right place. Same is the case with delete.
51
Inserting a new record:
Advantages:
Simple to understand.
Easy to maintain and organize
Loading a record requires only the record key.
Relatively inexpensive I/O media and devices can be used.
Easy to reconstruct the files.
The proportion of file records to be processed is high.
Disadvantages:
Expected Output: If record of student does not exist an appropriate message is displayed
otherwise thestudent details are displayed.
52
Assignment-12
Title:
Company maintains employee information as employee ID, name, designation, and salary.
Allow user to add, delete information of employee. Display information of particular
employee. If employee does not exist an appropriate message is displayed. If it is, then the system
displays the employee details. Use index sequential file to maintain the data.
Learning Objectives:
Learning Outcome:
Theory:
File organization refers to the relationship of the key of the record to the physical location
of that record in the computer file. File organization may be either physical file or a logical file.
A physical file is a physical unit, such as magnetic tape or a disk. A logical file on the other hand
is a complete set of records for a specific application or purpose. A logical file may occupy a part
of physical file or may extend over more than one physical file.
There are various methods of file organizations. These methods may be efficient for
certain types of access/selection meanwhile it will turn inefficient for other selections. Hence it is
up to the programmer to decide the best suited file organization method depending on his
requirement.
53
Indexed sequential access method (ISAM)
ISAM method is an advanced sequential file organization. In this method, records are stored in
the file using the primary key. An index value is generated for each primary key and mapped
with the record. This index contains the address of the record in the file.
If any record has to be retrieved based on its index value, then the address of the data block is fetched and the
record is retrieved from the memory.
Pros of ISAM:
In this method, each record has the address of its data block, searching a record in a huge
database is quick and easy.
This method supports range retrieval and partial retrieval of records. Since the index is based
on the primary key values, we can retrieve the data for the given range of value. In the same
way, the partial value can also be easily searched, i.e., the student name starting with 'JA' can
be easily searched.
Cons of ISAM
This method requires extra space in the disk to store the index value. When the new records
are inserted, then these files have to be reconstructed to maintain the sequence.
When the record is deleted, then the space used by it needs to be released. Otherwise, the
performance of the database will slow down.
54
Expected Output: If record of employee does not exist an appropriate message is displayed
otherwise theemployee’s details are displayed.
Conclusion: This program gives us the knowledge index sequential file organization.
55
Assignment-13
Title:
Design a mini project to implement Snake and Ladders Game using Python.
Learning Objectives:
Learning Outcome:
Analyze working of various python file scripts (snakes_ladders.py), resources files and sound
files.
Theory:
Python:
56
Test frameworks
Multimedia
Scientific computing
This Snakes and Ladders Game contains python file scripts (snakes_ladders.py), resources files and
sound files. The gameplay of the system, which is the user can choose an option either to play multiple
participant or with the computer.
Beginning of the game, the player needs to roll the dice and in the wake of moving it the game moves
the token consequently as indicated by the dice number. The interactivity is like the genuine one. Here,
the player likewise gets one more opportunity to roll the dice at whatever point he/she gets 6 number.
There are quantities of stepping stools and snakes in the game which causes the player to update or
minimization the square number. The player who arrives at the last square of the track is the champ.
create a “project name” after creating a project name click the “create” button.
57
Third after creating a python file, Name your python file after that click “enter“.
58