0% found this document useful (0 votes)
35 views121 pages

Chapger Java 1-5

Uploaded by

Ansh Narsale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views121 pages

Chapger Java 1-5

Uploaded by

Ansh Narsale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 121

DSU

CHAPTER 1
1) Explain ADT. List the Linear and Non-Linear data structures with example.
(Dec-17, May-19)

ANS] An ADT is a specified mathematical entity. It has a specific interface. A collection of signature of operations
that can be involved on an instance . It is a kind of abstraction which means the user does not know about the
operations taking place at the backend.
Linear data structures : Elements are arranged in a linear fashion. Types of linear data structures are:

I. List

II. Stack

Queue
Non-linear data structures:
Every data element can have many successors and predecessors.
Types of non-linear data Structures:

I. Tree

II. Graph

III.
2) Explain different types of data structure with example. (May-18, May-23)

ANS]Data structures are generally categorized into two classes:


Linear and Non-linear Structures
1.Linear: If the elements of a data structure are stored in a linear or sequential order, then it is a linear data
structure. Examples include arrays, linked lists, stacks, and queues. Linear data structures can be represented
in memory in two different ways. One way is to have to a linear relationship between elements by means of
sequential memory locations. The other way is to have a linear relationship between elements
by means of links.
Example:
2.Non-Linear: if the elements of a data structure are not stored in a
sequential order, then it is a non-linear data structure. The relationship
of adjacency is not maintained between elements of a non-linear datastructure.
Examples include trees and graphs:
3) What are various operations possible on data structures?
(Dec-18)

ANS] The data appearing in our data structure is processed by means of certain operations. In fact, the particular
data structure that once chooses for a

given situation depends largely on the frequency with which specific

operations are performed:

1. Insertion: Insertion means addition of a new data element in a data structure.

2. Deletion: Deletion means removal of a data element from a data structure if it is found.

3. Searching: Searching involves searching for the specified data element in a data structure.
4. Traversal: Traversal of a data structure means processing all the data Elements present in data
structure.
5. Sorting: Arranging data elements of a data structure in a specified order is called sorting.
6. Merging: Combining elements of two similar data structures to form a new data structure of the
same type, is called merging.
4)Define data structure. Differentiate linear and Non-linear data structure with
example. (Dec-19, Dec-22)

ANS] Data Structure


A data structure is a specialized format for organizing, processing,
retrieving and storing data.
DSU
CHAPTER 4
Weightage: 35 - 40
1) Describe Tries with an example. -DEC 18

ANS] (1) A trie is a tree-like data structure whose nodes store the letters of an alphabet. By structuring the nodes in a
particular way, words and strings can be retrieved from the structure by traversing down a branch path of the tree.
(2)A tree is a trie of degree P ≥ 2.
(3)Tries re useful for sorting words as a string of characters.

(4) In a trie, each path from the root to a leaf corresponds to one word.
(5)Root node is always null.

(6) To avoid confusion between words like THE and THEN, a special end marker symbol ‘\0’ is added at the end of each
word.
(7) Below fig shows the trie of the following words (THE, THEN, TIN, SIN, THIN, SING)
(8)Most nodes of a trie has at most 27 children one for each letter and for '\0’.
(9)Most nodes will have fewer than 27 children.
(10) A leaf node reached by an edge labelled '\0' cannot have any children and it need not be there.
2) Explain Threaded Binary tree in detail - MAY 19

ANS] In the linked representation of binary trees, more than one half of the link fields contain NULL values which
results in wastage of storage space. If a binary tree consists of n nodes then n+1 link fields contain NULL values. So
in order to effectively manage the space, a method was devised by Perlis and Thornton in which the NULL links are
replaced with special links known as threads. Such binary trees with threads are known as threaded binary trees.
Each node in a threaded binary tree either contains a link to its child node or thread to other nodes in the tree.
Types of Threaded Binary Tree
There are two types of threaded Binary Tree:
•One-way threaded Binary Tree
•Two-way threaded Binary Tree

One-way threaded Binary trees:

In one-way threaded binary trees, a thread will appear either in the right or left link field of a node. If it appears in
the right link field of a node then it will point to the next node that will appear on performing in order traversal. Such
trees are called Right threaded binary trees. If thread appears in the left field of a node then it will point to the
nodes inorder predecessor. Such trees are called Left threaded binary trees. Left threaded binary trees are used less
often as they don't yield the last advantages of right threaded binary trees. In one-way threaded binary trees, the
right link field of last node and left link field of first node contains a NULL. In order to distinguish threads from normal
links they are represented by dotted lines.
The above figure shows the inorder traversal of this binary tree yields D, B, E, A, C, F. When this tree is represented as a
right threaded binary tree, the right link field of leaf node D which contains a NULL value is replaced with a thread that
points to node B which is the inorder successor of a node D. In the same way other nodes containing values in the right
link field will contain NULL value.
Two-way threaded Binary Trees:
In two-way threaded Binary trees, the right link field of a node containing NULL values is replaced by a thread that points to
nodes inorder successor and left field of a node containing NULL values is replaced by a thread that points to nodes inorder
predecessor.

The above figure shows the inorder traversal of this binary tree yields D, B, E, G, A, C, F. If we consider the two-way
threaded Binary tree, the node E whose left field contains NULL is replaced by a thread pointing to its inorder predecessor
i.e. node B. Similarly, for node G whose right and left linked fields contain NULL values are replaced by threads such that
right link field points to its inorder successor and left link field points to its inorder predecessor. In the same way, other
nodes containing NULL values in their link fields are filled with threads.
In the above figure of two-way threaded Binary tree, we noticed that no left thread is possible for the first node and no
right thread is possible for the last node. This is because they don't have any inorder predecessor and successor
respectively. This is indicated by threads pointing nowhere. So in order to maintain the uniformity of threads, we
maintain a special node called the header node. The header node does not contain any data part and its left link field
points to the root node and its right link field points to itself. If this header node is included in the two-way threaded
Binary tree then this node becomes the inorder predecessor of the first node and inorder successor of the last node.
Now threads of left link fields of the first node and right link fields of the last node will point to the header node.
3) Define Binary Search Tree. Discuss the case of deletion of a node in binary
search tree if node has both the children. - DEC 22

ANS] A Binary Search Tree is a data structure used in computer science for organizing and storing data in a sorted
manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child
containing values less than the parent node and the right child containing values greater than the parent node.
This hierarchical structure allows for efficient searching, insertion, and deletion operations on the data stored in
the tree.

Case 1. Delete a Node with Both Children in BST


Note: Inorder predecessor can also be used.
Note: Inorder successor is needed only when the right child is not empty. In this
particular case, the inorder successor can be obtained by finding the minimum value
in the right child of the node.
4) Discuss the cases of deleting a node from binary search tree with suitable
example. -MAY 23

ANS]
5) Explain different types of tree traversals techniques with example. Also write
recursive function for each traversal technique. -MAY 18

ANS] TRAVERSING A BINARY TREE


Traversing a binary tree is the process of visiting each node in the tree exactly once in a systematic way.
a. Pre-order Traversal
To traverse a non-empty binary tree in pre-order, the following operations are performed recursively at each node.
The algorithm works by:
i. Visiting the root node.

ii. Traversing the left sub-tree, and finally


iii. Traversing the right sub-tree.

Example:
- The pre-order traversal of the tree is given as A, B, C. Root node first, the left sub-tree
next, and then the right
- sub-tree.
- Recursive Function
Void preorder (node * T) /* address of the root node is passed in T
*/
{
if (T! = NULL)
{
printf(“\n%d, T --> data);
preorder( T -->left);
preorder( T -->right);
}
}
b. In-order Traversal
- To traverse a non-empty binary tree in in-order, the following operations are performed recursively at each
node. The algorithm works by:
1. Traversing the left sub-tree.
2. Visiting the root node, and finally
3. Traversing the right sub-tree.
- Example:

The in-order traversal of the tree is given as B,A,C . Left sub-tree first, the root node next, and then the right sub-tree.
- Recursive Function
Void inorder (node * T) /* address of the root node is passed in T */
{
if (T! = NULL)
{
inorder( T -->left);
printf(“\n%d, T --> data);
inorder( T -->right);
}
}
c. Post-order Traversal
- To traverse a non-empty binary tree in post-order, the following operations are performed recursively at each node.
The algorithm works by:
1. Traversing the left sub-tree.
2. Traversing the right sub-tree, and finally
3. Visiting the root node.
- Example

The post-order traversal of the tree is given as B,C,A . Left sub-tree first, the right sub-tree and then the root node .
- Recursive Function
Void postorder (node * T) /* address of the root node is passed in T
*/
{
if (T! = NULL)
{
postorder( T -->left);
postorder( T -->right);
printf(“\n%d, T --> data);
}
}
6) Given the postorder and inorder traversal of a binary tree, construct the original tree:
Postorder: D E F B G L J K H C A
Inorder: D B F E A G C L J H K - DEC 18, DEC 19

ANS] Construction of Tree:


Step1: Select last element from the postorder as root node. So element A becomes root node. Divide the inorder
into left and right with respect to root node A.

Step 2: Traverse element D B F E from postorder as B comes in last B becomes child node of A and similarly traverse
G C L J H K in postorder C comes at last C becomes child node of A. Again with respect to B and C divide element
into left and right as shown below
Step 3: As D is single it becomes child node of B and for left node of B Traverse F E in postorder F comes at last so F
becomes child node of B. similarly, G and H become child node of C as shown below.

Step 4: As E is single it becomes child node of F. Traverse L J which is left element of node H in postorder as J
comes last J becomes child node of H as K is single it becomes another child node.
Step 5: As L is simgle it becomes child node of J
7) Construct binary search tree from given traversal sequences: Inorder Traversal: D E B
A C F G I H J Postorder Traversal: F E D C BA G H I J -DEC 22 & MAY 23 & DEC 23

ANS] Let us consider the below traversals: Inorder sequence: D B E A F C Preorder sequence: A B D E C F
In a Preorder sequence, the leftmost element is the root of the tree. So we know ‘A’ is the root for given
sequences. By searching ‘A’ in the Inorder sequence, we can find out all elements on the left side of ‘A’ is in the left
subtree and elements on right in the right subtree. So we know the below structure now.

/ \

/ \

D B E F C
We recursively follow the above steps and get the following tree.

A
/ \
/ \
B C
/ \ /
/ \ /
D E F
8)Write a program to implement Binary Search Tree (BST), Show BST for the
following inputs: 10,5,4,12,15,11,3 -DEC 17

ANS]
Code:
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *left;
struct node *right;
}node;
node *insert(node *t,int key)
{
if(t==NULL)
{
t=(node *)
(malloc(sizeof(node)));
t->data=key;
t->left=NULL;
t->right=NULL;
}
else
{
if(key>t->data)
t->right=insert(t->right,key);
else
t->left=insert(t->left,key);
}
return(t);
}
node *search(node *t,int key)
{
if(t==NULL)
return(NULL);
else if(t->data==key)
return(t);
else if(key>t->data)
return(search(t->right,key));
else
return(search(t->left,key));
}
node *max(node *t)
{
if(t==NULL)
return(NULL);
while(t->right!=NULL)
t=t->right;
return(t);
}
node *min(node *t)
{
if(t==NULL)
return(NULL);
while(t->left!=NULL)
t=t->left;
return(t);
}
void preorder(node *temp)
{
if(temp!=NULL)
{
printf("\n \n data: %d",temp->data);
preorder(temp->left);
preorder(temp->right);
}
}
void postorder (node *temp)
{
if(temp!=NULL)
{
postorder(temp->left);
postorder(temp->right);
printf("\n \n data: %d",temp->data);
}
}
void inorder(node *temp)
{
if(temp!=NULL)
{
postorder(temp->left);
printf("\n \n data: %d",temp->data);
postorder(temp->right);
}
}
int main()
{
struct node *root=NULL;
struct node *temp=NULL;
int c,key;
do
{
printf("\n 1.insert node \n 2.search \n 3.maximum number \n 4.minimum number \n 5.display in inorder format \n
6.display in postorfer format \n 7.display in preorder format
\n 8.exit \n");
printf("enter your choice:");
scanf("%d",&c);
switch(c)
{
case 1:printf("enter data:");
scanf("%d",&key);
if(root==NULL)
root=insert(root,key);
else
temp=insert(root,key);
break;
case 2:printf("enter key:");
scanf("%d",&key);
temp=search(root,key);
if(temp!=NULL)
printf("%d found",key);
else
printf("%d not found",key);
break;
case 3:temp=max(root);
printf("max=%d",temp-
>data);
break;
case 4:temp=min(root);
printf("min=%d",temp-
>data);
break;
case 5:inorder(root);
break;
case 6:postorder(root);
break;
case 7:preorder(root);
break;
}
}while(c!=8); return 0;
}
Output:
1.insert node
2.search
3.maximum number
4.minimum number
5.display in inorder
format
6.display in postorfer format
7.display in preorder format
8.exit
enter your choice:1
enter data:10
1.insert node
2.search
3.maximum number
4.minimum number
5.display in inorder format
6.display in postorfer format
7.display in preorder format
8.exit
enter your choice:1
enter data:55
1.insert node 2.search
3.maximum number
4.minimum number
5.display in inorder format
6.display in postorfer format
7.display in preorder format
8.exit
enter your choice:1
enter data:7
1.insert node
2.search
3.maximum number
4.minimum number
5.display in inorder format
6.display in postorfer format
7.display in preorder format
8.exit
enter your choice:2
enter key:7
7 found
1.insert node
2.search
3.maximum number
4.minimum number
5.display in inorder format
6.display in postorfer format
7.display in preorder format
8.exit
enter your choice:3
max=55
1.insert node
2.search
3.maximum number
4.minimum number
5.display in inorder
format
6.display in postorfer
format
7.display in preorder
format
8.exit
enter your choice:4
min=7
1.insert node
2.search
3.maximum number
4.minimum number
5.display in inorder
format
6.display in postorfer
format
7.display in preorder
format
8.exit
enter your choice:5
data: 7
data: 10
data: 55
1.insert node
2.search
3.maximum
number
4.minimum
number
5.display in
inorder
format
6.display in
postorfer
format
7.display in
preorder
format
8.Exit
enter your
choice:6
data: 7
data: 55
data: 10
1.insert node
2.search
3.maximum
number
4.minimum number
5.display in inorder format
6.display in postorfer format
7.display in preorder format
8.exit
enter your choice:7
data: 10
data: 7
data: 55
1.insert node
2.search
3.maximum number
4.minimum number
5.display in inorder format
6.display in postorfer format
7.display in preorder format
8.exit
enter your choice:8
9)Explain different cases for deletion of a node in binary search tree. Write
function for each case -MAY

ANS] When we delete a node, three possibilities arise.


1) Node to be deleted is leaf: Simply remove from the tree.

2) Node to be deleted has only one child: Copy the child to the node and delete the child
3) Node to be deleted has two children: Find inorder successor of the node. Copy contents of the inorder successor
to the node and delete the inorder successor. Note that inorder predecessor can also be used.

The important thing to note is, inorder successor is needed only when right child is not empty. In this particular case,
inorder successor can be obtained by finding the minimum value in right child of the node.
10) splay Tree and Trie -MAY 18

ANS] Splay trees are the self-balancing or self-adjusted binary search trees. In other words, we can say that the
splay trees are the variants of the binary search trees. The prerequisite for the splay trees that we should know
about the binary search trees.
As we already know, the time complexity of a binary search tree in every case. The time complexity of a binary
search tree in the average case is O(logn) and the time complexity in the worst case is O(n). In a binary search tree,
the value of the left subtree is smaller than the root node, and the value of the right subtree is greater than the
root node; in such case, the time complexity would be O(logn). If the binary tree is left-skewed or right-skewed,
then the time complexity would be O(n). To limit the skewness, the AVL and Red-Black tree came into the picture,
having O(logn) time complexity for all the operations in all the cases. We can also improve this time complexity by
doing more practical implementations, so the new Tree data structure was designed, known as a Splay tree.
Suppose we want to search 7 element in the tree, which is shown below:

To search any element in the splay tree, first, we will perform the standard binary search tree operation. As 7 is less
than 10 so we will come to the left of the root node. After performing the search operation, we need to perform
splaying. Here splaying means that the operation that we are performing on any element should become the root
node after performing some rearrangements. The rearrangement of the tree will be done through the rotations.
11) Expression Tree -MAY 19,DEC 17

ANS]Expression Tree
(1) Expression tree is a binary tree in which each internal node corresponds to operator and each leaf node
corresponds to operand.
(2) A binary expression tree is a specific kind of a binary tree used to represent expressions.

(3) The leaves of the binary expression tree are operands, such as constants or variable names, and the other
nodes contain operators.

(4) Assume the set of possible operators are {'+', '-', '*', '/'}. The set of possible operands are ['0' - '9']. See the
figure below, which is the binary expression tree for the expression (in in-fix notation): (((2+3)*9)+7).
Construction of Expression Tree:
Now For constructing expression tree we use a stack. We loop
through input expression and do following for every character.
1) If character is operand push that into stack
2) If character is operator pop two values from stack make them
its child and push current node again.

At the end only element of stack will be root of expression tree


12) What are expression trees? What are its advantages? Derive the expression
tree for the following algebraic expression (a + (b/c)) * ((d/e) -f) -(dec 18, dec 19)

ANS] Expression Tree: Compilers need to generate assembly code in which one operation is executed at a time
and the result is retained for other operations.
-Therefore, all expression has to be broken down unambiguously into separate operations and put into their
proper order.

- Hence, expression tree is useful which imposes an order on the execution of operations.

- Expression tree is a binary tree in which each internal node corresponds to operator and each leaf node
corresponds to operand

- Parentheses do not appear in expresion trees, but their intent remains intact in tree representation.
Construction of Expression Tree:
Now for constructing expression tree we use a stack. We loop through input expression and do following for
every character.
1) If character is operand push that into stack
2) If character is operator pop two values from stack make them its child and push current node again.

At the end only element of stack will be root of expression tree. Advantage:
1. Expression trees are using widely in LINQ to SQL, Entity Framework extensions where the runtime needs
to interpret the expression in a different way (LINQ to SQL and EF: to create SQL, MVC: to determine the
selected property or field).
2. Expression trees allow you to build code dynamically at runtime instead of statically typing it in the IDE
and using a compiler.
Expression Tree: (a + (b/c)) * ((d/e) - f)
13) Construct Huffman tree and determine the code for each symbol in
the String “BCAADDDCCACACAC” -DEC 23

ANS]
Huffman Coding
Huffman Coding is a technique of compressing data to reduce its size without losing any of the details. It was first
developed by David Huffman.

Huffman Coding is generally useful to compress the data in which there are frequently occurring characters.
How Huffman Coding works?

Suppose the string below is to be sent over a network.


Each character occupies 8 bits. There are a total of 15 characters in the above string. Thus, a total of 8 * 15 = 120 bits are
required to send this string.
Using the Huffman Coding technique, we can compress the string to a smaller size.
Huffman coding first creates a tree using the frequencies of the character and then generates code for each character.
Once the data is encoded, it has to be decoded. Decoding is done using the same tree.
Huffman Coding prevents any ambiguity in the decoding process using the concept of prefix code ie. a code associated
with a character should not be present in the prefix of any other code. The tree created above helps in maintaining the
property.
Huffman coding is done with the help of the following steps.

1. Calculate the frequency of each character in the string

Frequency of string

2. Sort the characters in increasing order of the frequency. These are stored in a priority queue Q.
Characters sorted according
to the frequency
3. Make each unique character as a leaf node.
4. Create an empty node z. Assign the minimum frequency to the
left child of z and assign the second minimum frequency to the
right child of z. Set the value of the z as the sum of the above
two minimum frequencies.Getting the sum of the least numbers
5. Remove these two minimum frequencies from Q and add the sum into the list of frequencies (* denote the
internal nodes in the figure above).
6. Insert node z into the tree.
7. Repeat steps 3 to 5 for all the characters.

Repeat steps 3 to 5 for all the


characters. Repeat steps 3 to 5 for all the characters.

8. For each non-leaf node, assign 0 to the left edge and 1 to the
right edge.Assign 0 to the left edge and 1 to the right edge
For sending the above string over a network, we have to send the tree as well as the above compressed-code.
The total size is given by the table below.

Character Frequency Code Size


A 5 11 5*2 = 10
B 1 100 1*3 = 3
C 6 0 6*1 = 6
D 3 101 3*3 = 9
4 * 8 = 32 bits 15 bits 28 bits

Without encoding, the total size of the string was 120 bits. After encoding the size is reduced to 32 + 15 + 28 =
75.
14) Construct Huffman tree and find the Huffman-codes for each symbol given below
with frequency of occurrence: - DEC 22
Value p g e r i
Frequency 20 17 33 25 40

ANS] Step 1: According to the Huffman coding we arrange all the elements (values) in ascending order of the
frequencies.
Value E A C F D B
Frequency 4 5 7 12 15 25

Step 2: Insert first two elements which have smaller frequency.


Value C EA F D B
Frequency 7 9 12 15 25

Step 3: Taking next smaller number and insert it at correct place.

Value F D CEA B
Frequency 12 15 16 25

Step 4: Next elements are F and D so we construct another subtree for F and D.
Value CEA B FD
Frequency 16 25 27

Step 5: Taking next value having smaller frequency then add it with CEA and insert it at correct place.

Value FD CEAB
Frequency 27 41

Step 6: We have only two values hence we can combined by adding them.
Huffman Tree
Value FDCEAB
Frequency 68
Now the list contains only one element i.e. FDCEAB having frequency 68
and this element (value) becomes the root of the Huffman tree.
15) Construct an AVL Tree with following data: 67 34 90 22 45 11 2 78 37 122
- DEC 22 & MAY 23 & DEC 23

ANS] AVL Tree


(1) AVL Trees are Self-Balanced Binary Search Trees.
(2) In AVL trees, the balancing factor of each node is either 0 or 1 or -1.
(3) Balance Factor of AVL Tree calculated as = Height of Left Sub-tree - Height of Right Sub-tree

Construction of AVL Trees -


(4) Insertion Operation is performed to construct the AVL Tree.
(5) Inserting the element in the AVL tree is same as the insertion performed in BST.
(6) After insertion, check the balance factor of each node of the resulting tree.
(7) After the insertion, the balance factor of each node is either 0 or 1 or -1, then the tree is considered to be
balanced, concludes the operation, and inserts the next element if any.
(8) After the insertion, the balance factor of at least one node is not 0 or 1 or -1, then the tree is considered to be
imbalanced, perform the suitable rotation to balance the tree, and after the tree is balanced, insert the next element
if any.
Step-by-Step Construction of the AVL Tree for the given Sequence 10 15 9 12 13 79 45 36 22:
16) AAVL Tree (dec 17)

Solution: ->An AVL tree is a height balance tree. These trees are binary search trees in which the
heights of two siblings are not permitted to differ by more than one. Searching time in a binary
search tree is O(h) where h is the height of the tree. For efficient searching it is necessary that the
height should be kept minimum.
-> A full binary search tree with n nodes will have a height of O(log n). In practice, it is very difficult
to control the height of a BST. It lies between O(n) to O(log n). An AVL tree is a close approximation
of full binary search tree.
->The balance factor of a node in a AVL tree could be -1, 0 or 1.
1. 0 indicates that the left and right subtrees are equal.
2. +1 means the height of the left subtree is one more than the height of the right subtree.
3. -1 indicates that the height of the right subtree is one more than the height of the left subtree.

Type of nodes Rotation


Left left Right
Right right Left
Right left i. right
ii. left
Left right i. left
ii. right
17) Demonstrate step by step insertion of the following elements an AVL tree
63, 9, 19, 18, 108, 81, 45
18) Explain B tree and B+ tree. (dec 17)

ANS] I.B tree


->A B-tree is a method of placing and locating files (called records or keys) in a database.

->The B-tree algorithm minimizes the number of times a medium must be accessed to locate a desired record,
thereby speeding up the process.

->Properties:
1. All the leaf nodes must be at same level.

2 . All nodes except root must have at least [m/2]-1 keys and maximum of m-1 keys.
3. All non leaf nodes except root (i.e. all internal nodes) must have at
least m/2 children. 4.If the root node is a non leaf node, then it must have at least 2 children.
5.A non leaf node with n-1 keys must have n number of children.
6.All the key values within a node must be in Ascending Order.
->example:

II. B+ Tree

->A B+ tree is a data structure often used in the implementation of database indexes.
->Each node of the tree contains an ordered list of keys and pointers to lower level nodes in
the tree. These pointers can be thought of as being between each of the keys.
->Properties:
1. The root node points to at least two nodes.
2. All non-root nodes are at least half full.
3. For a tree of order m, all internal nodes have m-1 keys and m pointers.
4. A B+-Tree grows upwards.
5. A B+-Tree is balanced.
6. Sibling pointers allow sequential searching.
->example:
19) Construct a B-tree of order 3 by inserting the following given elements as
1,2,3,4,5,6,7,8,9,10 -DEC 22 & MAY 23

ANS] Construct a B-Tree of Order 3 by inserting numbers from 1 to 10.


22) Compare B tree and B+ tree -MAY 23
23) Construct B+ tree of order 3 for the following dataset: -MAY 23

ANS] Problem: Insert the following key values 6, 16, 26, 36, 46 on a B+ tree with order = 3. Solution:

Step 1: The order is 3 so at maximum in a node so there can be only 2 search key values. As insertion happens on a
leaf node only in a B+ tree so insert search key value 6 and 16 in increasing order in the node. Below is the
illustration of the same:
Step 2: We cannot insert 26 in the same node as it causes an overflow in the leaf node, We have to split the leaf node
according to the rules. First part contains ceil((3-1)/2) values i.e., only 6. The second node contains the remaining
values i.e., 16 and 26. Then also copy the smallest search key value from the second node to the parent node i.e., 16 to
the parent node. Below is the illustration of the same:

Step 3: Now the next value is 36 that is to be inserted after 26 but in that node, it causes an overflow again in that leaf
node. Again follow the above steps to split the node. First part contains ceil((3-1)/2) values i.e., only 16. The second
node contains the remaining values i.e., 26 and 36. Then also copy the smallest search key value from the second node
to the parent node i.e., 26 to the parent node. Below is the illustration of the same: The illustration is shown in the
diagram below.
Step 4: Now we have to insert 46 which is to be inserted after 36 but it causes an overflow in the leaf node. So we split
the node according to the rules. The first part contains 26 and the second part contains 36 and 46 but now we also have
to copy 36 to the parent node but it causes overflow as only two search key values can be accommodated in a node.
Now follow the steps to deal with overflow in the non-leaf node. First node contains ceil(3/2)-1 values i.e. ’16’. Move the
smallest among remaining to the parent i.e ’26’ will be the new parent node. The second node contains the remaining
keys i.e ’36’ and the rest of the leaf nodes remain the same. Below is the illustration of the same:
DSU
CHAPTER 5
1) What is graph? Explain methods to represent graph. (DEC 22,19,18)(MAY
23,18)

ANS] Graph is a data structure that consists of following two components:


1. A finite set of vertices also called as nodes.
2. A finite set of ordered pair of the form (u, v) called as edge. The pair is ordered because (u, v) is not same as (v,
u) in case of a directed graph(digraph). The pair of the form (u, v) indicates that there is an edge from vertex u to
vertex v. The edges may contain weight/value/cost.

Following is an example of undirected graph with 5 vertices.


There are two most commonly used representations of a graph.
1. Adjacency Matrix:
- Adjacency Matrix is a 2D array of size V x V where V is the number
of vertices in a graph.
- Let the 2D array be adj[ ][ ], a slot adj[i][j] = 1 indicates that there is
an edge from vertex i to vertex j.
- Adjacency matrix for undirected graph is always symmetric.
- Adjacency Matrix is also used to represent weighted graphs. - If
adj[i][j] = w, then there is an edge from vertex i to vertex j with weight w.
- Following is adjacency matrix representation of the above graph.
2. Adjacency List
- An array of lists is used. Size of the array is equal to the number of vertices.
- Let the array be array[]. An entry array[i] represents the list of vertices adjacent to the ith
vertex.
- This representation can also be used to represent a weighted graph.
- The weights of edges can be represented as lists of pairs.
- Following is adjacency list representation of the above graph.
2) Expression Trees (DEC 17)

Ans]
->Expression tree as name suggests is nothing but expressions arranged in a tree-like data
structure. Each node in an expression tree is an expression.
->it is a tree with leaves as operands of the expression and nodes contain the operators.
Similar to other data structures, data interaction is also possible in an expression tree.
->For example, an expression tree can be used to represent mathematical formula x < y
where x, < and y will be represented as an expression and arranged in the tree like structure.
->Expression tree is an in-memory representation of a lambda expression. It holds the actual
elements of the query, not the result of the query.
->Expression trees are mainly used for analyzing, evaluating and modifying expressions,
especially complex expressions.
3) Graph Traversal Techniques (DEC 17)(MAY 18)

Ans]There are two standard methods of graph traversal.


1. Breadth-first search:
- Breadth-first search (BFS) is a graph search algorithm that begins at the root node and
explores all the neighbouring nodes.
- Then for each of those nearest nodes, the algorithm explores their unexplored neighbour
nodes, and so on, until it finds the goal.
- That is, we start examining the node A and then all the neighbours of A are examined.
Algorithm for Breadth-first search:
- Step 1: SET STATUS=1(ready state) for each node in G
- Step 2: Enqueue the starting node A and set its STATUS=2 (waiting state)
- Step 3: Repeat Steps4and5until QUEUE is empty
- Step 4: Dequeueanode N. Process it and set its STATUS=3 (processed state).
- Step 5: Enqueue all the neighbours of N that are in the ready state (whose STATUS=1) and
set their STATUS=2 (waiting state) [END OF LOOP]
- Step 6: EXIT
Applications of Breadth-First Search Algorithm:
- Breadth-first search can be used to solve many problems such as:
- Finding all connected components in a graph G.
- Finding all nodes within an individual connected component.
- Finding the shortest path between two nodes, u and v, of an unweighted graph.
- Finding the shortest path between two nodes, u and v, of a weighted graph.

2. Depth-first Search
- The depth-first search algorithm (Fig. 13.22) progresses by expanding the starting node of G
and then going deeper and deeper until the goal node is found, or until a node that has no
children is encountered.
- When a dead-end is reached, the algorithm backtracks, returning to the most recent node
that has not been completely explored.
- depth-first search begins at a starting node A which becomes the current node.
- Then, it examines each node N along a path P which begins at A.
- That is, we process a neighbour of A, then a neighbour of neighbour of A, and so on
Algorithm for depth-first search:
- Step 1: SET STATUS=1(ready state) for each node in G
- Step 2: Push the starting nodeAon the stack and set its STATUS=2(waiting state)
- Step 3: Repeat Steps4and5until STACK is empty
- Step 4: Pop the top node N. Process it and set its STATUS=3(processed state)
- Step 5: Push on the stack all the neighbours ofNthat are in the ready state (whose STATUS=1)
and set their STATUS=2(waiting state) [END OF LOOP]
- Step 6: EXIT
4) Explain Depth First search (DFS) Traversal with an example. Write the
recursive function for DFS (MAY 19)

Ans] Depth-first Search:


- The depth-first search algorithm (Fig. 13.22) progresses by expanding the starting node of G
and then going deeper and deeper until the goal node is found, or until a node that has no
children is encountered.
- When a dead-end is reached, the algorithm backtracks, returning to the most recent node
that has not been completely explored.
- depth-first search begins at a starting node A which becomes the current node.
- Then, it examines each node N along a path P which begins at A.
- That is, we process a neighbour of A, then a neighbour of neighbour of A, and so on.
Algorithm for depth-first search:
- Step 1: SET STATUS=1(ready state) for each node in G
- Step 2: Push the starting nodeAon the stack and set its STATUS=2(waiting state)
- Step 3: Repeat Steps4and5until STACK is empty
- Step 4: Pop the top node N. Process it and set its STATUS=3(processed state)
- Step 5: Push on the stack all the neighbours ofNthat are in the ready state (whose STATUS=1)
and set their STATUS=2(waiting state) [END OF LOOP]
- Step 6: EXIT

Example:
Adjacency list for G:
1. A: B, C, D
2. B: C, E
3. C: E
4. D: C, F
5. E: A
6. F: C
7.G: D, F, H
8. H: C
5) Write a function in C for DFS traversal of graph. Explain DFS graph traversal.
with suitable example. (DEC 22)

Ans:-Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data
structures.
The algorithm starts at the root node (selecting some arbitrary node as the root node in the
case of a graph) and explores as far as possible along each branch before backtracking. Extra
memory, usually a stack, is needed to keep track of the nodes discovered so far along a
specified branch which helps in backtracking of the graph.
Example:
DSU
CHAPTER 6
1.Write a program in ‘C’ to implement Merge sort. ( MAY 2018 )

⮚ PROGRAM
#include <stdio.h>
#include <conio.h>
#define size 100
void merge(int a[], int, int, int);
void merge_sort(int a[],int, int);
void main()
{
int arr[size], i, n; printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
printf("\n Enter the elements of the array: ");
for(i=0;i<n;i++)
{
scanf("%d", &arr[i]);
}
merge_sort(arr, 0, n-1);
printf("\n The sorted array is: \n");
for(i=0;i<n;i++)
printf(" %d\t", arr[i]);
getch();
}
void merge(int arr[], int beg, int mid, int end)
{
int i=beg, j=mid+1, index=beg, temp[size], k;
while((i<=mid) && (j<=end))
{
if(arr[i] < arr[j])
{
temp[index] = arr[i];
i++;
}
Else
{
temp[index] = arr[j];
j++;
}
index++;
}
if(i>mid)
{
while(j<=end)
{
temp[index] = arr[j];
j++;
index++;
}
}
Else
{
while(i<=mid)
{
temp[index] = arr[i];
i++;
index++;
}
}
for(k=beg;k<index;k++)
arr[k] = temp[k];
}
void merge_sort(int arr[], int beg, int end)
{
int mid;
if(beg<end)
{
mid = (beg+end)/2;
merge_sort(arr, beg, mid);
merge_sort(arr, mid+1, end);
merge(arr, beg, mid, end);
}
}

OUTPUT:
Enter the number of elements in the array :5
Enter the elements of the array: 12 45 32 67 88
The sorted array is: 12 32 45 67 88
2. Using Linear probing and Quadratic probing, insert following values in the
hash table of size 10. Show how many collisions occur in each iteration 28, 55, 71,
67, 11, 10, 90, 44. -( MAY 2018 )
3. Huffman Encoding ( MAY 2018, MAY 2019, DEC 2017, DEC 2018, DEC 2019)

⮚ Huffman Code:
- Huffman code is an application of binary trees with minimum weighted external path length is to obtain an
optimal set for messages M1, M2, …Mn - Message is converted into a binary string.
- Huffman code is used in encoding that is encrypting or compressing the text in the WSSS communication
system.
- It uses patterns of zeros and ones in communication system these are used at sending and receiving end.
- suppose there are n standard message M1, M2, ……Mn. Then the frequency of each message is considered,
that is message with highest frequency is given priority for the encoding.
- The tree is called encoding tree and is present at the sending end. – The decoding tree is present at the
receiving end which decodes the string to get corresponding message.
- The cost of decoding is directly proportional to the number of bits in the transmitted code is equal to distance
of external node from the root in the tree.
Example
4.Topological Sorting ( MAY 2019, DEC 2017, NOV 2022,NOV 2023)

⮚ • Topological sort of a directed acyclic graph (DAG) G is defined as a linear ordering of its nodes in which
each node comes before all nodes to which it has outbound edges. Every DAG has one or more number
of topological sorts.
• A topological sort of a DAG G is an ordering of the vertices of G such that if G contains an edge (u, v),
then u appears before v in the ordering
• Note that topological sort is possible only on directed acyclic graphs that do not have any cycles.
• For a DAG that contains cycles, no linear ordering of its vertices is possible.
• In simple words, a topological ordering of a DAG G is an ordering of its vertices such that any directed
path in G traverses the vertices in increasing order.
• Topological sorting is widely used in scheduling applications, jobs, or tasks. The jobs that have to be
completed are represented by nodes, and there is an edge from node u to v if job u must be completed
before job v can be started.
• A topological sort of such a graph gives an order in which the given jobs must be performed.

• The two main steps involved in the topological sort algorithm include:
1.Selecting a node with zero in-degree
2.Deleting N from the graph along with its edges
• Algorithm For topological Sorting
Step 1: Find the in-degree INDEG(N) of every node in the graph
Step 2: Enqueue all the nodes withazero in-degree
Step 3: Repeat Steps4and5until the QUEUE is empty
Step 4: Remove the front nodeNof the QUEUE by setting FRONT=FRONT+1
Step 5: Repeat for each neighbourMof node N: a) Delete the edge from N to M by setting INDEG(M)=INDEG(M)-1 b)
IF INDEG(M) =,then
Enqueue M, that is, addM to the rear of the queue [END OF INNER
LOOP] [END OF LOOP]
Step 6: Exit
• Example:
Topological sort can be given as:
• A, B, C, D, E
• A, B, C, E, D
• A, C, B, D, E
• A, C, B, E, D
5. Write a program to implement Binary Search on sorted set of integers.
-( DEC 2017)

⮚ Program:
#include<stdio.h>
int n;
int binary(int a[],int n,int x) impliment Quick sort.
{
int low=0,high=n-1,mid;
while(low<=high)
{
mid=(low+high)/2;
if(x==a[mid])
return(mid);
else if(x<a[mid]) scanf("%d",&y);
high=mid-1; j=binary(a,n,y);
else i=j;
low=mid+1; if(j==-1)
} printf("element not found");
return(-1); else
} {
int main() printf("\n %d occurred at position=%d \n",y,i+1);
{ }
int y,i,j; return 0;
printf("enter the size of the array:"); }
scanf("%d",&n);
int a[n];
printf("entered sorted list of array:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("enter the number to be searched:");
Output:
enter the size of the array:5
entered sorted list of array:1 2 5 8 9
enter the number to be searched:5
5 occurred at position=3
6. Write a program to implement Quick sort. Show the steps to sort the given
numbers: 25,13,7,34,56,23,13,96,14,2 (DEC 2017)

⮚ Program:
#include<stdio.h>
#include<stdlib.h>
void quick(int a[40],int first,int last)
{
int pivot,j,i,temp;

if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j)
{
while(a[i]<=a[pivot] && i<last)
i++;
while(a[j]>a[pivot])
j--;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[pivot];
a[pivot]=a[j];
a[j]=temp;
quick(a,first,j-1);
quick(a,j+1,last);
}
}
void main()
{
int a[20],n,i;
printf("enter the no. of elements:");
scanf("%d",&n);
printf("enter the elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}

quick(a,0,n-1);
printf("sorted elements are:");
for(i=0;i<n;i++)
{
printf("%d \t",a[i]);
}
}
Output:
enter the no. of elements:10
enter the elements:25 13 7 34 56 23 13 96 14 2
sorted elements are:2 7 13 13 14 23 25 34 56 96
Steps:
7. Write a function in C to implement binary search. (DEC 2018)

⮚ Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval
covering the whole array. If the value of the search key is less than the item in the middle of the
interval,narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the
value is found or the interval is empty.
C function to implement binary search:
int binary_search(int sorted_list[], int low, int high, int element)

{
int middle;
while (low <= high)
{
middle = low + (high - low)/2;
if (element > sorted_list[middle])
low = middle + 1;
else if (element < sorted_list[middle])
high = middle - 1;
else
return middle;
}
return -1;
}
8. How does the Quicksort technique work? Give C function for the same.
(DEC 2018)

- Quick sort is the fastest internal sorting algorithm with the time and space complexity = O(n log n).

- The basic algorithm to sort an array a[] of n elements can be describe recursively as follows:

1. If n <= 1, then return

2. Pick any element V in array a[]. This element is called as pivot. Rearrange elements of the array by moving all
elements xᵢ > V right of V and all elements xᵢ ≤ V left of V. if the place of the V after rearrangement is j, all
elements with value less than V, appear in a[0], a[1] … a[j-1] and all those with value greater than V appear in
a[j+1] … a[n-1]
3. Apply quick sort recursively to a[0] … a[j-1] and to a a[j+1] … a[n-1]
Entire array will thus be sorted by as selecting an element V.
a) Partitioning the array around V.
b) Recursively, sorting the left partition.
c) Recursively, sorting the right partition.
9. What is hashing? What properties should a good hash function demonstrate?
(DEC 2018)

⮚ Hashing:
- Hashing is a technique by which updating or retrieving any entry can be achieved in constant time O(1).
- In mathematics, a map is a relationship between two sets. A map M is a set of pairs, where each pair is in the
form of (key, value). For a given key, its corresponding value can be found with the help of a function that maps
keys to values. This function is known as the hash function.
- So, given a key k and a hash function h, we can compute the value/location of the value v by the formula v =
h(k).

- Usually, the hash function is a division modulo operation, such as h(k)=k mod size, where size is the size of the
data structure that holds the values.
- Hashing is a way with the requirement of keeping data sorted.
- In best case time complexity is of constant order O(1) in worst case O(n)
- Address or location of an element or record, x, is obtained by computing some arithmetic function f.f(key) gives the
address of x in the table.
- Table used for storing of records is known as hash table.
- Function f(key) is known as hash function.
10. Given an array int a[] = {69, 78, 63, 98, 67, 75, 66, 90, 81}. Calculate address of
a[5] if base address is 1600. (DEC 2018)
11. Write C function to implement insertion sort.
(DEC 2019)

⮚ Insertion Sort
Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands.
Algorithm
// Sort an arr[] of size n
insertionSort(arr, n)
Loop from i = 1 to n-1.
Pick element arr[i] and insert it into sorted sequence arr[0…i-1]
-C function
/* Function to sort an array using insertion sort*/
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
12. What is hashing? Hash the following data in table of size 10 using linear
probing and quadratic probing. Also find the number of collisions. 63, 84, 94, 77,
53, 87, 23, 55, 10, 44. (DEC 2019)

⮚ Hashing:
- Hashing is a technique by which updating or retrieving any entry can be achieved in constant time
O(1).
- In mathematics, a map is a relationship between two sets. A map M is a set of pairs, where each pair
is in the form of (key, value). For a given key, its corresponding value can be found with the help of a
function that maps keys to values. This function is known as the hash function.
- So, given a key k and a hash function h, we can compute the value/location of the value v by the
formula v = h(k).
- Usually, the hash function is a division modulo operation, such as h(k)=k mod size, where size is the
size of the data structure that holds the values.
- Hashing is a way with the requirement of keeping data sorted.
- In best case time complexity is of constant order O(1) in worst case O(n)
- Address or location of an element or record, x, is obtained by computing some arithmetic function f.f(key) gives the
address of x in the table.
- Table used for storing of records is known as hash table.
- Function f(key) is known as hash function.
13. Given an array int a[]={23, 55, 63, 89, 45, 67, 85, 99}. Calculate address of a[5]
if base address is 5100. (DEC 2019)

You might also like