Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

Question Bank

Unit - 1

1. What is a data structure? Why do we need data structures?


A data structure is a specialized format for organizing, processing, retrieving and storing
data.
In general, data structures are used to implement the physical forms of abstract data types.
Data structures are a crucial part of designing efficient software. They also play a critical role in
algorithm design and how those algorithms are used within computer programs
2. How data structures are classified? Differentiate linear and non-linear data structure.

S.NO Linear D.S Non-Linear D.S


1 Data elements are arranged in a Data elements are attached in
linear order where each and every hierarchically manner.
element is attached to its previous
and next adjacent.
2 single level is involved. multiple levels are involved.
3 Its implementation is easy in While its implementation is
comparison to non-linear data complex in comparison to linear
structure. data structure.
4 data elements can be traversed in data elements can’t be traversed
a single run only. in a single run only.
5 memory is not utilized in an memory is utilized in an efficient
efficient way. way.
6 Its examples are: array, stack, While its examples are: trees and
queue, linked list, etc. graphs.
7 Applications: are application Applications: are Artificial
software development. Intelligence and image
processing.

3. Define ADT (Abstract Data Type). Mention the features of ADT.

An ADT is a mathematical model of a data structure that specifies the type of data stored, the
operations supported on them, and the types of parameters of the operations

It exports a type.
It exports a set of operations. This set is called interface.
Operations of the interface are the one and only access mechanism to the type's data structure.

4. What are the ways of implementing linked list? What are the types of linked lists?

Singly Linked List : It is the most common. Each node has data and a pointer to the next node.

Doubly Linked List : We add a pointer to the previous node in a doubly-linked list. Thus, we can go in
either direction: forward or backward.
Circular Linked List : A circular linked list is a variation of a linked list in which the last element is
linked to the first element. This forms a circular loop.

Singly linked lists.


Doubly linked lists.
Circular linked lists.
Circular doubly linked lists.

5. How the singly linked lists can be represented? How the doubly linked list can be represented?

Singly L.L
struct LinkedList{ int data; struct LinkedList *next; };

Doubly L.L
struct node {

int data;
struct node *next;
struct node *prev; }

6. List down the applications of List. What are the advantages of a linked list? Mention the demerits of
linked list.

Applications

1. Implementation of stacks and queues


2. Implementation of graphs: Adjacency list representation of graphs is the most popular which uses a
linked list to store adjacent vertices.
3. Dynamic memory allocation: We use a linked list of free blocks.
4. Maintaining a directory of names
5. Performing arithmetic operations on long integers
6. Manipulation of polynomials by storing constants in the node of the linked list
7. representing sparse matrices

Advantages
1) Dynamic Data Structure:
2) No Memory Wastage:
3) Implementation:
4) Insertion and Deletion Operation:
1) Memory Usage:
2) Random Access:
3) Reverse Traversal:

Disadvantage
1) Use of pointers is more in linked lists hence, complex and requires more memory.
2) Searching an element is costly and requires O(n) time complexity.
3) Traversing is more time consuming and reverse traversing is not possible in singly linked
lists.
4) Random access is not possible due to dynamic memory allocation.

7. What are the operations performed in the list? What are the merits and demerits of array
implementation of lists?

Operation in list:
Insertion − Adds an element at the beginning of the list.
Deletion − Deletes an element at the beginning of the list.
Display − Displays the complete list.
Search − Searches an element using the given key.
Delete − Deletes an element using the given key.
Advantages
1) In arrays, the elements can be accessed randomly by using the index number.
2) Arrays allocate memory in contiguous memory locations for all its elements. Hence there is
no chance of extra memory being allocated in case of arrays. This avoids memory overflow or
shortage of memory in arrays. Using arrays, other data structures like linked lists, stacks, queues,
trees, graphs etc can be implemented.
3) Two-dimensional arrays are used to represent matrices.
Disadvantages
1) The number of elements to be stored in an array should be known in advance.
2) An array is a static structure (which means the array is of fixed size). Once declared the size
of the array cannot be modified. The memory which is allocated to it cannot be increased
or decreased.
3) Insertion and deletion are quite difficult in an array as the elements are stored in consecutive
memory locations and the shifting operation is costly.
4) Allocating more memory than the requirement leads to wastage of memory space and less
allocation of memory also leads to a problem.

8. Write the program for array implementation of lists.

#include<stdio.h>
#include<conio.h>
#define MAX 10

void create();
void insert();
void deletion();
void search();
void display();
int a,b[20], n, p, e, f, i, pos;

void main()
{
//clrscr();
int ch;
char g='y';

do
{
printf("\n main Menu");
printf("\n 1.Create \n 2.Delete \n 3.Search \n 4.Insert \n 5.Display\n 6.Exit \n");
printf("\n Enter your Choice");
scanf("%d", &ch);
switch(ch)
{
case 1:
create();
break;

case 2:
deletion();
break;

case 3:
search();
break;

case 4:
insert();
break;

case 5:
display();
break;

case 6:
exit();
break;

default:
printf("\n Enter the correct choice:");
}
printf("\n Do u want to continue:::");
scanf("\n%c", &g);
}
while(g=='y'||g=='Y');
getch();
}
void create()
{
printf("\n Enter the number of nodes");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n Enter the Element:",i+1);
scanf("%d", &b[i]);
}

void deletion()
{
printf("\n Enter the position u want to delete::");
scanf("%d", &pos);
if(pos>=n)
{
printf("\n Invalid Location::");
}
else
{
for(i=pos+1;i<n;i++)
{
b[i-1]=b[i];
}
n--;
}
printf("\n The Elements after deletion");
for(i=0;i<n;i++)
{
printf("\t%d", b[i]);
}
}
void search()
{
printf("\n Enter the Element to be searched:");
scanf("%d", &e);

for(i=0;i<n;i++)
{
if(b[i]==e)
{
printf("Value is in the %d Position", i);
}
else
{
printf("Value %d is not in the list::", e);
continue;
}
}
}

void insert()
{
printf("\n Enter the position u need to insert::");
scanf("%d", &pos);

if(pos>=n)
{
printf("\n invalid Location::");
}
else
{
for(i=MAX-1;i>=pos-1;i--)
{
b[i+1]=b[i];
}
printf("\n Enter the element to insert::\n");
scanf("%d",&p);
b[pos]=p;
n++;
}
printf("\n The list after insertion::\n");

display();
}

void display()
{
printf("\n The Elements of The list ADT are:");
for(i=0;i<n;i++)
{
printf("\n\n%d", b[i]);
}
}

9. Write a C program for linked list implementation of list.

// Linked list implementation in C

#include <stdio.h>
#include <stdlib.h>

// Creating a node
struct node {
int value;
struct node *next;
};

// print the linked list value


void printLinkedlist(struct node *p) {
while (p != NULL) {
printf("%d ", p->value);
p = p->next;
}
}

int main() {
// Initialize nodes
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;

// Allocate memory
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));

// Assign value values


one->value = 1;
two->value = 2;
three->value = 3;

// Connect nodes
one->next = two;
two->next = three;
three->next = NULL;

// printing node-value
head = one;
printLinkedlist(head);
}

10. Explain the operations of circularly linked lists.


Insertion
if there are 1000 elements, and if the insert has to be done after the 999th Node, we would need
to iterate over these 999 nodes, hence this insertion has the Time complexity of O(N), N being
the number of elements in the circular linked list.
void insertNodeAtBeginning(int value) {

Node newNode = new Node(value);


Node oldFirstNode = last.next;
newNode.next = oldFirstNode;
last.next = newNode;
}

Deletion
we might need to transverse the circular linked list to delete the node. This is required to find the
Previous node, so that its next can be adjusted to remove the culprit node from the circular
linked list chain.
So deletion takes O(N) time complexity, and as it takes no extra space to execute, its space
complexity is O(1) i.e. content space complexity.
Node deleteNode(int valueOfNodeToDelete) {

if (last == null)
return null;
if (last.value == valueOfNodeToDelete && last.next == last) {
last = null;
return last;
}
Node temp = last;
}

Display
To display the circular linked list, we need to transverse from the last Pointer until we reach back
to it. As we transverse over the Nodes, we can print their values.
void displayList() {

Node temp = last;


if (last != null) {
do {
System.out.print(temp.value + " ");
temp = temp.next;
} while (temp != last);
}
}

<---------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------->

Unit-2

1. Define Stack. What are the operations of the stack? What are the applications of stack?

A stack is a conceptual structure consisting of a set of homogeneous elements and is based on the
principle of last in first out (LIFO).
Operattion:
Push, which adds an element to the collection, and.
Pop, which removes the most recently added element that was not yet removed.
Application:
A Stack can be used for evaluating expressions consisting of operands and operators.
Stacks can be used for Backtracking, i.e., to check parenthesis matching in an expression.
It can also be used to convert one form of expression to another form.
It can be used for systematic Memory Management.

2. How the stack is implemented by linked list? Write the routine to pop an element from a stack.

In linked list implementation of stack, the nodes are maintained non-contiguously in the memory. Each
node contains a pointer to its immediate successor node in the stack. Stack is said to be overflown if
the space left in the memory heap is not enough to create a node.
POP Algorithm:
1. Step 1 − Checks if the stack is empty.
2. Step 2 − If the stack is empty, produces an error and exit.
3. Step 3 − If the stack is not empty, accesses the data element at which top is pointing.
4. Step 4 − Decreases the value of top by 1.
5. Step 5 − Returns success.
3. Define queue. What are the operations of a queue? What are the types of queue?

A queue is defined as a linear data structure that is open at both ends and the operations are performed
in First In First Out (FIFO) order.
Operation:
Enqueue() - Insertion of elements to the queue.
Dequeue() - Removal of elements from the queue.
Display
Types:
Simple Queue.
Circular Queue.
Priority Queue.
Double Ended Queue.

4. What are the methods to implement queue in C? How the queue is implemented by linked list?

Methods to implement queue:


Enqueue- adding an element in the queue if there is space in the queue.
Dequeue- Removing elements from a queue if there are any elements in the queue.
Front- get the first item from the queue.
Rear- get the last item from the queue.
isEmpty/isFull- checks if the queue is empty or full.
In a linked queue, each node of the queue consists of two parts i.e. data part and the link part. Each
element of the queue points to its immediate next element in the memory.
In the linked queue, there are two pointers maintained in the memory i.e. front pointer and rear
pointer.

5. Write the routine to delete an element from a queue. What are the applications of queue?

Algorithm for Delete


1. STEP 1 START.
2. STEP 2 Store the element to delete.
3. STEP 3 If front == -1 then Queue Underflow.
4. STEP 4 Element deleted from queue is cqueue_arr[front].
5. STEP 5 if (front==rear) then front= -1; rear= -1; else goto step 6.
6. STEP 6 if (front == MAX - 1) then front= 0 else goto step 7.
7. STEP 7 front = front + 1.
Application
Managing requests on a single shared resource such as CPU scheduling and disk scheduling.
Handling hardware or real-time systems interrupts.
Handling website traffic.
Routers and switches in networking.
Maintaining the playlist in media players.

6. What are enqueue and dequeue operations?

Enqueue is a queue operation where you add an item at the back of a queue. at the rear end
if the queue is full, then it is said to be an Overflow conditon.
Enqueue is an accessing the content while removing it from the front end of the queue. at the front
end
if the queue is empty, then it is said to be an Underflow condition.

7. Distinguish between stack and queue.

S.NO Stack Queue


1 Stacks are based on the LIFO Queues are based on the FIFO
principle, i.e., the element inserted principle, i.e., the element inserted
at the last, is the first element to at the first, is the first element to
come out of the list. come out of the list.
2 Insert operation is called push Insert operation is called enqueue
operation. operation.
3 Delete operation is called pop Delete operation is called dequeue
operation. operation.
4 Stack is used in solving problems Queue is used in solving problems
works on recursion. having sequential processing.
5 Stack does not have any types. Queue is of three types –
1. Circular Queue 2. Priority queue
3. double-ended queue.
6 Can be considered as a vertical Can be considered as a horizontal
collection visual. collection visual.

7 Insertion and deletion in stacks Insertion and deletion in queues


takes place only from one end of takes place from the opposite ends
the list called the top. of the list. The insertion takes place
at the rear of the list and the
deletion takes place from the front
of the list.
8 Elements are inserted and removed Elements are inserted and removed
at the same time. at the different time.

8. (1). Convert the infix (a+b)*(c+d)/f into postfix & prefix


Expression. (2). Write postfix from of the expression –A+B-C+D?

Prefix for (a+b)*(c+d)/f


+*ab+/cdf
Postfix for (a+b)*(c+d)/f
ab+cd+*/f
Postfix for –A+B-C+D
-ABCD++-

9. Define priority queue with diagram and explain the operations.

A priority queue is a special type of queue in which each element is associated with a priority value.
And, elements are served on the basis of their priority. That is, higher priority elements are served first.
However, if elements with the same priority occur, they are served according to their order in the
queue.
Operations:
Insert
Insert the new element at the end of the tree.
Delete
Select the element to be deleted.
Swap it with the last element.
Remove the last element.
Peep
Peek operation returns the maximum element from Max Heap or minimum element from
Min Heap without deleting the node.
Extract Max/Min
Extract-Max returns the node with maximum value after removing it from a Max Heap
whereas Extract-Min returns the node with minimum value after removing it from Min
Heap.
11. Explain how to evaluate arithmetic expressions using stack.

The stack organization is very effective in evaluating arithmetic expressions. Expressions are usually
represented in what is known as Infix notation, in which each operator is written between two
operands (i.e., A + B). With this notation, we must distinguish between ( A + B )*C and A + ( B * C )
by using either parentheses or some operator-precedence convention. Thus, the order of operators and
operands in an arithmetic expression does not uniquely determine the order in which the operations are
to be performed.
1. Prefix notation
1. It refers to the notation in which the operator is placed before its two operands. Here no
parentheses are required, i.e., +AB
2. Postfix notation
1. It refers to the analogous notation in which the operator is placed after its two operands.
Again, no parentheses is required in Reverse Polish notation, i.e., AB+
3. Steps:
1. Convert the expression in Reverse Polish notation( post-fix notation).
2. Push the operands into the stack in the order they appear.
3. When any operator encounters then pop two topmost operands for executing the
operation.
4. After execution push the result obtained into the stack.
5. After the complete execution of expression, the final result remains on the top of the
stack.
6. Infix notation: (2+4) * (4+6) Post-fix notation: 2 4 + 4 6 + *Result: 60

<---------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------->

Unit-3

1. Define non-linear data structure. Define tree and leaf.


It is a form of data structure where the data elements don't stay arranged linearly or
sequentially.
user can't traverse all of its elements in a single run.
Tree: A tree is non-linear and a hierarchical data structure consisting of a collection of nodes such that
each node of the tree stores a value and a list of references to other nodes (the “children”).
Leaf: The node which does not have any child node.

2. Define Tree. Explain the tree traversals with algorithms and examples.

A tree is non-linear and a hierarchical data structure consisting of a collection of nodes such that each
node of the tree stores a value and a list of references to other nodes (the “children”).

Inorder Traversal :
In this traversal method, the left subtree is visited first, then the root and later the right sub-tree.
We should always remember that every node may represent a subtree itself.
Algorithm:
Step 1 − Recursively traverse left subtree.
Step 2 − Visit root node.
Step 3 − Recursively traverse right subtree.
Example: In order traversal for the above-given figure is 4 2 5 1 3.
Preorder Traversal :
Process all nodes of a tree by processing the root, then recursively processing all subtrees.
Algorithm:
Step 1- Visit the root.
Step 2- Traverse the left subtree, i.e., call Preorder(left->subtree)
Step 3- Traverse the right subtree, i.e., call Preorder(right->subtree)
Example: Preorder traversal for the above-given figure is 1 2 4 5 3.
Postorder Traversal :
Postorder traversal is used to delete the tree. Postorder traversal is also useful to get the postfix
expression of an expression tree.
Algorithm:
Step 1- Traverse the left subtree, i.e., call Postorder(left->subtree)
Step 2- Traverse the right subtree, i.e., call Postorder(right->subtree)
Step 3- Visit the root.
Example: Postorder traversal for the above-given figure is 4 5 2 3 1
3. What is a ordered tree? What is meant by directed tree? List out the steps involved in deleting a
node from a binary search tree.

A tree where the children of every node are ordered.


Directed tree: a directed acyclic graph (DAG) whose underlying undirected graph is a tree.
Steps:
Step 1- Node to be deleted is the leaf:
Simply remove from the tree.
Step 2- Node to be deleted has only one child:
Copy the child to the node and delete the child.\
Step 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

4. Explain binary search tree in detail.

A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentioned properties −

The value of the key of the left sub-tree is less than the value of its parent (root) node's key.

The value of the key of the right sub-tree is greater than or equal to the value of its parent (root)
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 − left_subtree (keys) < node (key) ≤ right_subtree (keys).
Representation:
BST is a collection of nodes arranged in a way where they maintain BST properties. Each node
has a key and an associated value. While searching, the desired key is compared to the keys in
BST and if found, the associated value is retrieved.
Operation :

Search − Searches an element in a tree.


Insert − Inserts an element in a tree.

Pre-order Traversal − Traverses a tree in a pre-order manner.

In-order Traversal − Traverses a tree in an in-order manner.

Post-order Traversal − Traverses a tree in a post-order manner.

5. Construct an expression tree for the expression (a + b * c) + ((d * e + 1) * g). Give the outputs when
you apply
preorder,inorder and postorder traversals.

6. Construct a binary tree having the following traversal


sequences:
Preorder traversal A B C D E F G H I
Inorder traversal B C A E D G H F I
7. Explain AVL tree in detail.

An AVL tree is a type of binary search tree. Named after it's inventors Adelson, Velskii, and Landis,
AVL trees have the property of dynamic self-balancing in addition to all the other properties exhibited
by binary search trees.

A BST is a data structure composed of nodes.

1. Each tree has a root node (at the top)


2. The root node has zero, one, or two child nodes
3. Each child node has zero, one, or two child nodes
4. Each node has up to two children
5. For each node, its left descendants are less than the current node, which is less than the right
descendants

8. Explain b tree and B+ tree in detail.


B-Tree is known as a self-balancing tree as its nodes are sorted in the inorder traversal. In B-tree, a
node can have more than two children. B-tree has a height of logM N (Where ‘M’ is the order of tree
and N is the number of nodes). And the height is adjusted automatically at each update. In the B-tree
data is sorted in a specific order, with the lowest value on the left and the highest value on the right. To
insert the data or key in B-tree is more complicated than a binary tree. Some conditions must be held
by the B-Tree:
All the leaf nodes of the B-tree must be at the same level.
Above the leaf nodes of the B-tree, there should be no empty sub-trees.
B- tree’s height should lie as low as possible.
B+ tree eliminates the drawback B-tree used for indexing by storing data pointers only at the leaf
nodes of the tree. Thus, the structure of leaf nodes of a B+ tree is quite different from the structure of
internal nodes of the B tree. It may be noted here that, since data pointers are present only at the leaf
nodes, the leaf nodes must necessarily store all the key values along with their corresponding data
pointers to the disk file block, to access them. Moreover, the leaf nodes are linked to providing ordered
access to the records. The leaf nodes, therefore form the first level of the index, with the internal nodes
forming the other levels of a multilevel index. Some of the key values of the leaf nodes also appear in
the internal nodes, to simply act as a medium to control the searching of a record.

9. Explain threaded binary tree in detail.Write the advantages of threaded binary tree.

The idea of threaded binary trees is to make inorder traversal faster and do it without stack and without
recursion. A binary tree is made threaded by making all right child pointers that would normally be
NULL point to the inorder successor of the node (if it exists).
There are two types of threaded binary trees.
Single Threaded: Where a NULL right pointers is made to point to the inorder successor (if
successor exists)
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.
Advantages:
No need for stacks or recursion: Unlike binary trees, threaded binary trees do not require a
stack or recursion for their traversal.
Optimal memory usage: Another advantage of threaded binary tree data structure is that it
decreases memory wastage. In normal binary trees, whenever a node’s left/right pointer is
NULL, memory is wasted. But with threaded binary trees, we are overcoming this problem by
storing its inorder predecessor/successor.
Time complexity: In-order traversal in a threaded binary tree is fast because we get the next
node in O(1) time than a normal binary tree that takes O(Height). But insertion and deletion
operations take more time for the threaded binary tree.
Backward traversal: In a double-threaded binary tree, we can even do a backward traversal.

10. Define Graph. Define a biconnected graph. Define shortest path problem.

Graph: Non-linear data structures made up of a finite number of nodes or vertices and the edges that
connect them.
Bioconnected Graph: is a connected graph that is not broken into disconnected pieces by deleting any
single vertex (and its incident edges).
Shortest path problem: the problem of finding a path between two vertices (or nodes) in a graph such
that the sum of the weights of its constituent edges is minimized.

11. What is a directed graph? What is an undirected graph? Define adjacent nodes?

Directed Path: is a set of vertices and a collection of directed edges that each connects an ordered pair
of vertices.
Unidirected Path: a set of nodes and a set of links between the nodes.
Adjacent nodes: Two node or vertices are adjacent if they are connected to each other through an edge.

12. Discuss algorithms of Breadth First Search (BFS) and Depth First Search (DFS) traversal for a
Graph. Explain with an example.

Depth First Search:


The general idea behind depth first traversal is that, starting from any random vertex, single path
is traversed until a vertex is found whose all the neighbors are already been visited. The search
then backtracks on the path until a vertex with unvisited adjacent vertices is found and then
begin traversing a new path starting from that vertex, and so on. This process will continue until
all the vertices of the graph are visited.

//Algorithm for DFS()


Step1. Initialize all the vertices to ready state (STATUS = 1)
Step2. Put the starting vertex into STACK and change its status to waiting (STATUS = 2)
Step 3: Repeat Step 4 and 5 until STACK is EMPTY
Step 4: POP the top vertex from STACK, Process the vertex, Change its status to processed state
(STATUS = 3)
Step 5: PUSH all the neighbors in the ready state (STATUS = 1) to the STACK and change their
status to waiting state (STATUS = 2)
Step 6: Exit.
Breadth First Search:
The general idea behind breadth first traversal is that, start at a random vertex, then visit all of its
neighbors, the first vertex that we visit, say is at level ‘0’ and the neighbors are at level ‘1’. After
visiting all the vertices at level ‘1’ we then pick one of these vertexes at level ‘1’ and visit all its
unvisited neighbors, we repeat this procedure for all other vertices at level ‘1’. Say neighbors of
level 1 are in level 2, now we will visit the neighbors of all the vertices at level 2, and this
procedure will continue.
// algorithm for BFS()
Step1. Initialize all the vertices to ready state (STATUS = 1)
Step2. Put the starting vertex into QUEUE and change its status to waiting (STATUS = 2)
Step 3: Repeat Step 4 and 5 until QUEUE is EMPTY
Step 4: Remove the front vertex from QUEUE, Process the vertex, Change its status to
processed state (STATUS = 3)
Step 5: ADD all the neighbors in the ready state (STATUS = 1) to the RARE of the QUEUE and
change their status to waiting state (STATUS = 2)
Step 6: Exit.

13. Explain Difference between BFS and DFS.

S.NO Parameters BFS DFS


1 Stands for Breadth FirstSearch. Depth First Search.
2 Data Structure Uses Queue data Uses Stack data
structure for finding structure.
the shortest path.
3 Conceptual Difference BFS builds the tree DFS builds the tree
level by level. sub-tree by sub-tree.
4 Suitable for BFS is more suitable DFS is more suitable
for searching vertices when there are
closer to the given solutions away from
source. source.
5 Memory BFS requires more DFS requires less
memory. memory.

14. Explain a minimum spanning tree with suitable example.

A minimum spanning tree is a special kind of tree that minimizes the lengths (or “weights”) of the
edges of the tree.

A spanning tree is a tree that includes the fewest possible edges from the graph and each node is
connected once and only once.
A minimum spanning tree algorithm is a method used to find the minimum spanning tree of a graph.
These algorithms usually start off by seeking out the smallest weighted edge in the graph, but the
methods on how to continue after the first step can differ. The end goal is the same: create a subset
with the smallest weighted edges possible that still define a spanning tree. There are many different
algorithms that can be used to find the minimum spanning tree and the best algorithm will depend on
the size of the graph and the context of the situation. In this article, Kruskal's algorithm and Prim's
algorithm will be explained and analyzed. Graphs may have several unique minimum spanning trees.
That is, all the spanning trees have the same minimum sum of the weighted edges, but might include
different edges. This can happen when a graph has several edges with the same weight.

15. Explain Kruskal’s algorithm with suitable example.

Kruskal's Algorithm is used to find the minimum spanning tree for a connected weighted graph. The
main target of the algorithm is to find the subset of edges by using which we can traverse every vertex
of the graph. It follows the greedy approach that finds an optimum solution at every stage instead of
focusing on a global optimum.
Algorithm:
1. Step 1: Create a forest F in such a way that every vertex of the graph is a separate tree.
2. Step 2: Create a set E that contains all the edges of the graph.
3. Step 3: Repeat Steps 4 and 5 while E is NOT EMPTY and F is not spanning
4. Step 4: Remove an edge from E with minimum weight
5. Step 5: IF the edge obtained in Step 4 connects two different trees, then add it to the forest F (fo
r combining two trees into one tree).
6. ELSE
7. Discard the edge
8. Step 6: END

Example

Construct the minimum spanning tree (MST) for the given graph using Kruskal’s Algorithm-

Solution-
To construct MST using Kruskal’s Algorithm,
Simply draw all the vertices on the paper.
Connect these vertices using edges with minimum weights such that no cycle gets formed.
Step-01:
Step 2

Step 3

Step 4
Step 5

Step 6
Step 7

Since all the vertices have been connected / included in the MST, so we stop.
Weight of the MST

= Sum of all edge weights

= 10 + 25 + 22 + 12 + 16 + 14

= 99 units

<---------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------->

Unit 4

1. Explain hashing. What is Extendible Hashing?


Hashing in the data structure is a technique of mapping a large chunk of data into small tables
using a hashing function.
It is also known as the message digest function. It is a technique that uniquely identifies a
specific item from a collection of similar items.

Extendible hashing: is a dynamically updateable disk-based index structure which implements a


hashing scheme utilizing a directory. The index is used to support exact match queries, i.e., find the
record with a given key

2. Explain Rehashing in detail.

the process of re-calculating the hash code of already stored entries and moving them to a bigger size
hash map when the number of elements in the map reaches the maximum threshold value.
Two Steps:
Create a larger table.
Create a new hash function
Use the new hash function to add the existing data items from the old table to the new table.
Rehashing Techniques:
Linear Probing
Two pass file Creation
Separate Overflow Area
Double Hashing
Synonym Chaining
Bucket Chaining
Bucket Addressing

3. Explain concepts of fields, records and files.

Fields : It is defined as a unit of meaningful information about an entity like date of flight, name of
passenger, address etc.
Records : It is a collection of units of information about a particular entity. Passenger of an airplane,
an employee of an organization, or an article sold from a store.
Files : A collection of records involving a set of entities with certain aspects in common and organized
for some particular purpose is called a file. For example collection of records of all passengers.
4. Explain Indexed and Relative/Random File Organization. ( 8 M)

Indexed : Indexing is a data structure technique that helps to speed up data retrieval. As we can
quickly locate and access the data in the database, it is a must-know data structure that will be needed
for database optimizing. Indexing minimizes the number of disk accesses required when a query is
processed.
Relative/Random File Organization : A relative record file contains records ordered by their relative
key , a record number that represents the location of the record relative to where the file begins.
Records are stored randomly but accessed directly. To access a file stored randomly, a record key
is used to determine where a record is stored on the storage media. Magnetic and optical disks
allow data to be stored and accessed randomly.

5. Brief about Collision- Resolution Techniques.

If two keys hash to the same index, the corresponding records cannot be stored in the same location.
So, if it's already occupied, we must find another location to store the new record, and do it so that we
can find it when we look it up later on.
To give an idea of the importance of a good collision resolution strategy, consider the following result,
derived using the birthday paradox. Even if we assume that our hash function outputs random indices
uniformly distributed over the array, and even for an array with 1 million entries, there is a 95% chance
of at least one collision occurring before it contains 2500 records.

There are a number of collision resolution techniques, but the most popular are chaining and open
addressing.

6. What are the applications of Hashing?

Message Digest.
Password Verification.
Data Structures(Programming Languages)
Compiler Operation.
Rabin-Karp Algorithm.
Linking File name and path together.
Game Boards.
Graphics.
<---------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------->

Unit -5

1. Explain the sorting algorithms.

A sorting algorithm is a method for reorganizing a large number of items into a specific order, such as
alphabetical, highest-to-lowest value or shortest-to-longest distance. Sorting algorithms take lists of
items as input data, perform specific operations on those lists and deliver ordered arrays as output. The
many applications of sorting algorithms include organizing items by price on a retail website and
determining the order of sites on a search engine results page (SERP).
A few examples of sorting algorithms:
The bubble sort algorithm repeatedly proceeds through the list, comparing pairs of adjacent
items and exchanging their positions if they are in the wrong order. The algorithm passes
through the list in that way until the entire list has been sorted.
The insertion sort algorithm starts by putting the first two items in order and then compares the
third item with the second one, swapping positions if necessary and repeats that action with the
first item. Subsequent items subjected to the same process often don't have to be moved far
through the sorted items.
The Shell sort algorithm compares and sorts items at intervals, decreasing the size of the interval
at each pass through the list. The final passes through are a bubble sort but it's much faster
because items are already closer to their desired positions.
The quicksort algorithm selects a random item in the list, compares all the other items to it and
organizes them into those that belong before the selected item and those that belong after it. That
means that none of the items have to be compared with those in the other group again.
The method proceeds by selecting random items within those two groups of items and repeating
the process. Eventually, some other method such as the insertion algorithm does the final
sorting.

2. Explain the searching algorithms.

A search algorithm is the step-by-step procedure used to locate specific data among a collection of
data. It is considered a fundamental procedure in computing. In computer science, when searching for
data, the difference between a fast application and a slower one often lies in the use of the proper
search algorithm.

All search algorithms make use of a search key in order to proceed with the procedure. Search
algorithms are expected to return a success or a failure status, usually denoted by Boolean true/false.
Different search algorithms are available, and the performance and efficiency of the same depend on
the data and on the manner in which they are used.
A linear search algorithm is considered the most basic of all search algorithms. The best perhaps is
binary search. There are other search algorithms such as the depth-first search algorithm, breadth-first
algorithm, etc. The efficiency of a search algorithm is measured by the number of times a comparison
of the search key is done in the worst case. The notation used in search algorithms is O(n), where n is
the number of comparisons done. It gives the idea of the asymptotic upper bound of execution time
required for the algorithm with respect to a given condition.
Search cases in search algorithms can be categorized as best case, average case and worst case. In
some algorithms, all the three cases might be asymptotically the same, whereas in some others there
could be a large difference. The average behavior of the search algorithm helps in determining the
usefulness of the algorithm.

3. What is searching? Explain Binary search algorithm with example and also find its time complexity.

Searching : the process of finding the required information from a collection of items stored as
elements in the computer memory.
Binary Search Algorithm
In this article, we will discuss the Binary Search Algorithm. Searching is the process of finding
some particular element in the list. If the element is present in the list, then the process is called
successful, and the process returns the location of that element. Otherwise, the search is called
unsuccessful.
Linear Search and Binary Search are the two popular searching techniques. Here we will discuss
the Binary Search Algorithm.
Binary search is the search technique that works efficiently on sorted lists. Hence, to search an
element into some list using the binary search technique, we must ensure that the list is sorted.
Binary search follows the divide and conquer approach in which the list is divided into two
halves, and the item is compared with the middle element of the list. If the match is found then,
the location of the middle element is returned. Otherwise, we search into either of the halves
depending upon the result produced through the match.
Algorithm:
1. Step 1: set beg = lower_bound, end = upper_bound, pos = - 1
2. Step 2: repeat steps 3 and 4 while beg <=end
3. Step 3: set mid = (beg + end)/2
4. Step 4: if a[mid] = val
5. set pos = mid
6. print pos
7. go to step 6
8. else if a[mid] > val
9. set end = mid - 1
10. else
11. set beg = mid + 1
12. [end of if]
13. [end of loop]
14. Step 5: if pos = -1 print "value is not present in the array"
15. [end of if]
16. Step 6: exit

4. What is searching? Explain Linear search algorithm with example and also find its time complexity.

Searching : the process of finding the required information from a collection of items stored as
elements in the computer memory.
In this article, we will discuss the Linear Search Algorithm. Searching is the process of finding some
particular element in the list. If the element is present in the list, then the process is called successful,
and the process returns the location of that element; otherwise, the search is called unsuccessful.
Two popular search methods are Linear Search and Binary Search. So, here we will discuss the
popular searching technique, i.e., Linear Search Algorithm.
Linear search is also called as sequential search algorithm. It is the simplest searching
algorithm. In Linear search, we simply traverse the list completely and match each element of
the list with the item whose location is to be found. If the match is found, then the location of the
item is returned; otherwise, the algorithm returns NULL.
It is widely used to search an element from the unordered list, i.e., the list in which items are not
sorted. The worst-case time complexity of linear search is O(n).
Algorithm:

1. Step 1: set pos = -1


2. Step 2: set i = 1
3. Step 3: repeat step 4 while i <= n
4. Step 4: if a[i] == val
5. set pos = i
6. print pos
7. go to step 6
8. [end of if]
9. set ii = i + 1
10. [end of loop]
11. Step 5: if pos = -1
12. print "value is not present in the array "
13. [end of if]
14. Step 6: exit

5. Discuss the Algorithm of merge sort with an example.

1. step 1: start
2. step 2: declare array and left, right, mid variable
3. step 3: perform merge function.

if left > right


return
mid= (left+right)/2
mergesort(array, left, mid)
mergesort(array, mid+1, right)
merge(array, left, mid, right)

4. step 4: Stop

An example of merge sort. First, divide the list into the smallest unit (1 element), then compare each
element with the adjacent list to sort and merge the two adjacent lists. Finally, all the elements are
sorted and merged.

6. Explain how to sort the elements by using selection sort.


In this article, we will discuss the Selection sort Algorithm. The working procedure of selection sort is
also simple. This article will be very helpful and interesting to students as they might face selection
sort as a question in their examinations. So, it is important to discuss the topic.
In selection sort, the smallest value among the unsorted elements of the array is selected in every
pass and inserted to its appropriate position into the array. It is also the simplest algorithm. It is
an in-place comparison sorting algorithm. In this algorithm, the array is divided into two parts,
first is sorted part, and another one is the unsorted part. Initially, the sorted part of the array is
empty, and unsorted part is the given array. Sorted part is placed at the left, while the unsorted
part is placed at the right.
In selection sort, the first smallest element is selected from the unsorted array and placed at the
first position. After that second smallest element is selected and placed in the second position.
The process continues until the array is entirely sorted.

The average and worst-case complexity of selection sort is O(n2), where n is the number of
items. Due to this, it is not suitable for large data sets.

7. Write a C program to sort the elements using bubble sort, insertion sort and radix sort.

Bubble Sort

#include <stdio.h>

// Function to swap elements

void swap(int *a, int *b)

int temp = *a;

*a = *b;

*b = temp;

// bubble sort function

void bubbleSort(int array[], int n)

int i, j;

for (i = 0; i < n-1; i++)

for (j = 0; j < n-i-1; j++) if (array[j] > array[j+1])

swap(&array[j], &array[j+1]);
}

// Function to print the elements of an array

void printArray(int array[], int size)

int i;

for (i=0; i < size; i++)

printf("%d ", array[i]);

printf("n");

// Main Function

int main()

int array[] = {89, 32, 20, 113, -15};

int size = sizeof(array)/sizeof(array[0]);

bubbleSort(array, size);

printf("Sorted array: n");

printArray(array, size);

return 0;

Output
Sorted array:
-15 20 32 89 113

Insertion Sort:

#include <math.h>

#include <stdio.h>

// Insertion Sort Function

void insertionSort(int array[], int n)

int i, element, j;

for (i = 1; i < n; i++) { element = array[i]; j = i - 1; while (j >= 0 && array[j] >

element) {

array[j + 1] = array[j];

j = j - 1;

}
array[j + 1] = element;

// Function to print the elements of an array

void printArray(int array[], int n)

int i;

for (i = 0; i < n; i++)

printf("%d ", array[i]);

printf("n");

// Main Function

int main()

int array[] = { 122, 17, 93, 3, 56 };

int n = sizeof(array) / sizeof(array[0]);

insertionSort(array, n);

printArray(array, n);

return 0;

Output:
3 17 56 93 122

Radix Sort

#include <stdio.h>

int getMax(int a[], int n) {


int max = a[0];
for(int i = 1; i<n; i++) {
if(a[i] > max)
max = a[i];
}
return max; //maximum element from the array
}
void countingSort(int a[], int n, int place) // function to implement counting sort
{
int output[n + 1];
int count[10] = {0};

// Calculate count of elements


for (int i = 0; i < n; i++)
count[(a[i] / place) % 10]++;

// Calculate cumulative frequency


for (int i = 1; i < 10; i++)
count[i] += count[i - 1];

// Place the elements in sorted order


for (int i = n - 1; i >= 0; i--) {
output[count[(a[i] / place) % 10] - 1] = a[i];
count[(a[i] / place) % 10]--;
}

for (int i = 0; i < n; i++)


a[i] = output[i];
}

// function to implement radix sort


void radixsort(int a[], int n) {

// get maximum element from array


int max = getMax(a, n);

// Apply counting sort to sort elements based on place value


for (int place = 1; max / place > 0; place *= 10)
countingSort(a, n, place);
}

// function to print array elements


void printArray(int a[], int n) {
for (int i = 0; i < n; ++i) {
printf("%d ", a[i]);
}
printf("\n");
}

int main() {
int a[] = {181, 289, 390, 121, 145, 736, 514, 888, 122};
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArray(a,n);
radixsort(a, n);
printf("After applying Radix sort, the array elements are - \n");
printArray(a, n);
}

Output:
Before Sorting array elements are -
181 289 390 121145 736 514 888 122
After applying Radix sort, the array elements are -
121 122 145 181 289 390 514 736 888

8. Write a C program to perform searching operations using linear and binary search.

#include <stdio.h>
#include <stdlib.h>
main()
{

/* Declare variables - array_of_number,search_key,i,j,low,high*/


int array[100],search_key,i,j,n,low,high,location,choice;
void linear_search(int search_key,int array[100],int n);
void binary_search(int search_key,int array[100],int n);

clrscr();
/* read the elements of array */
printf("ENTER THE SIZE OF THE ARRAY:");
scanf("%d",&n);
printf("ENTER THE ELEMENTS OF THE ARRAY:\n");
for(i=1;i<=n;i++)
{
scanf("%d",&array[i]);
}
/* Get the Search Key element for Linear Search */
printf("ENTER THE SEARCH KEY:");
scanf("%d",&search_key);
/* Choice of Search Algorithm */
printf("___________________\n");
printf("1.LINEAR SEARCH\n");
printf("2.BINARY SEARCH\n");
printf("___________________\n");
printf("ENTER YOUR CHOICE:");
scanf("%d",&choice);
switch(choice)
{
case 1:
linear_search(search_key,array,n);
break;
case 2:
binary_search(search_key,array,n);
break;
default:
exit(0);
}

getch();
return 0;
}
/* LINEAR SEARCH */
void linear_search(int search_key,int array[100],int n)
{
/*Declare Variable */
int i,location;
for(i=1;i<=n;i++)
{
if(search_key == array[i])
{
location = i;
printf("______________________________________\n");
printf("The location of Search Key = %d is %d\n",search_key,location);
printf("______________________________________\n");
}
}
}
/* Binary Search to find Search Key */
void binary_search(int search_key,int array[100],int n)
{
int mid,i,low,high; low = 1;
high = n;
mid = (low + high)/2; i=1;
while(search_key != array[mid])
{
if(search_key <= array[mid])
{
low = 1; high = mid+1; mid = (low+high)/2;
}
else
{
low = mid+1; high = n; mid = (low+high)/2;
}
}
printf("__________________________________\n");
printf("location=%d\t",mid);
printf("Search_Key=%d Found!\n",search_key);
printf("__________________________________\n");
10. Write a procedure for sorting a given list of elements using the Quick sort method. Show the
division of the list in the quick sort for a list of 10 numbers.

Algorithm :

1. Step 1 : QUICKSORT (array A, start, end)


2. Step 2 : { if (start < end)
3. Step 3 : 2 { p = partition(A, start, end)
4. Step 4 : 4 QUICKSORT (A, start, p - 1)
5. Step 5 : 5 QUICKSORT (A, p + 1, end) }}

You might also like