Mcs 21 Impquestion
Mcs 21 Impquestion
(b) Write an algorithm for the following : (i) Insert an element at the end of a
linked list (ii) Delete an element from linked list
(a)
- Algorithm 2: Merge sort (time complexity: O(n log n), space complexity:
O(n))
In this example, bubble sort has a lower space complexity but a higher time
complexity, while merge sort has a higher space complexity but a lower time
complexity. This trade-off is common in algorithm design, where reducing
time complexity often increases space complexity and vice versa.
(b)
4. Set the new node as the next node of the last node
Algorithm:
2. If the node is the head, update the head to the next node
3. Otherwise, update the previous node's next pointer to the node's next
node
Note: These algorithms assume a singly linked list and do not handle edge
cases like deleting the last node or inserting at an invalid position.
(d) Write and explain Prim’s algorithm for finding Minimum Cost Spanning
Tree (MCST).
(c) A circular queue is a type of queue where the last element is connected
to the first element, forming a circle. This means that when we reach the end
of the queue, we can wrap around to the beginning of the queue. A circular
queue can be implemented using an array by using modular arithmetic to
calculate the indices.
Implementation:
(d) Prim's algorithm is a greedy algorithm used to find the Minimum Cost
Spanning Tree (MCST) of a weighted undirected graph.
Steps:
Explanation:
- Prim's algorithm starts with an arbitrary node and grows the MST by adding
nodes and edges greedily.
- The algorithm terminates when all nodes are included in the MST.
Note: |E| is the number of edges, and |V| is the number of vertices in the
graph.
Write an algorithm for insertion sort. Write step by step working of this
algorithm for sorting the following list of data : 8, 10, 25, 8, 16, 27, 2, 45
Step-by-Step Working:
2. Compare the next element (10) with the first element (8)
3. Compare the next element (25) with the previous elements (8, 10)
- Since 25 is greater than both 8 and 10, move to the next element
4. Compare the next element (8) with the previous elements (8, 10, 25)
- Since 8 is less than 10, swap them
5. Compare the next element (16) with the previous elements (8, 8, 10, 25)
6. Compare the next element (27) with the previous elements (8, 8, 10, 25,
16)
- Since 27 is greater than all previous elements, move to the next element
7. Compare the next element (2) with the previous elements (8, 8, 10, 25,
16, 27)
8. Compare the next element (45) with the previous elements (2, 8, 8, 10,
16, 25, 27)
- Since 45 is greater than all previous elements, move to the next element
Note: In each step, we compare the current element with the previous
elements and swap them if necessary, until the list is sorted.
Draw AVL tree by inserting the following elements one by one : 8, 13, 27, 9,
12, 15, 10, 35, 25
1. Insert 8:
2. Insert 13:
8
13
3. Insert 27:
13
27
4. Insert 9:
9 13
27
5. Insert 12:
9 13
12 27
6. Insert 15:
/
9 13
12 15
27
7. Insert 10:
9 13
10 12
15
27
8. Insert 35:
9 13
10 12
15
27
35
9. Insert 25:
9 13
10 12
15
27
25 35
The final AVL tree is balanced, with a height of 4. Note that the tree is
rebalanced after each insertion to maintain the AVL property.
(b) Explain indexed sequential file organization with the help of an example.
3. For each term, add the coefficients and store the result in R(x)
4. If a term is present in one polynomial but not the other, add it to R(x) with
the same coefficient
5. Return R(x)
Example:
P(x) = 3x^2 + 2x + 1
Q(x) = 2x^2 – x + 4
Example:
- Marks
- An index block contains pointers to the blocks where each student’s record
is stored
Index Block:
-1|1
-2|2
-3|1
-…
Data Blocks:
Block 1:
- 1 | John | 85
- 3 | Jane | 90
Block 2:
To retrieve a student’s record, we first search the index block for the roll
number, then use the block number to directly access the data block
containing the record.
This organization allows for efficient sequential access for operations like
printing all records, as well as direct access for operations like retrieving a
specific record.
5. (a) Write and explain algorithm for binary search. Also, explain
applications of binary search.
b) What is Breadth First Search (BFS) ? Explain difference between BFS and
Depth First Search (DFS).
Red-Black Tree:
2. If the tree is empty, make the new node the root and color it black.
3. Otherwise, find the appropriate location for the new node and insert it.
4. If the new node’s parent is red, rebalance the tree by rotating nodes and
recoloring them.
5. If the new node’s grandparent is red, recolor the grandparent and its
children.
Step-by-Step:
3. If the target value is less than the middle element, search the left half of
the array.
4. If the target value is greater than the middle element, search the right half
of the array.
5. Repeat steps 2-4 until the target value is found or the search space is
empty.
Applications of Binary Search:
BFS is a graph traversal algorithm that explores all nodes at the current level
before moving to the next level. It uses a queue data structure to keep track
of nodes to visit.
- BFS explores nodes level by level, while DFS explores nodes depth by
depth.
- BFS is used for finding shortest paths and connected components, while
DFS is used for finding a path between two nodes and testing connectivity.
Output: Matrix C = A × B
Step-by-Step:
- Calculate the dot product of the i-th row of A and the j-th column of B.
Explanation:
- Time complexity is O(n^3) because we have three nested loops (two for the
matrices and one for the dot product).
(b)Sparse Matrix:
Step-by-Step:
Example:
Input Matrix:
```
[1, 0, 0, 0, 0]
[0, 2, 0, 0, 0]
[0, 0, 3, 0, 0]
[0, 0, 0, 4, 0]
[0, 0, 0, 0, 5]
[0, 0, 0, 0, 0]
```
Output:
```
[(0, 0, 1), (1, 1, 2), (2, 2, 3), (3, 3, 4), (4, 4, 5)]
```
(d) What is a binary search ? Write an algorithm for binary search and find
its complexity.
Algorithm:
1. Initialize an array `arr` of size `n` to store the linked list elements.
- Find the first available index `i` in `arr` (where `next[i] == -1`).
- Set `next[i]` to the current `next` index (or `-1` if at the end).
- Print `arr[i]`.
Binary Search:
Binary search is an efficient algorithm for finding an element in a sorted
array.
Algorithm:
5. If `target < arr[mid]`, search the left half of the array (repeat steps 2-5).
6. If `target > arr[mid]`, search the right half of the array (repeat steps 2-5).
Complexity:
Note: The algorithm assumes a sorted array. If the array is not sorted, sorting
it first would add extra time complexity.
A Splay Tree is a self-balancing binary search tree data structure that keeps
frequently accessed elements at the root of the tree, making search and
access operations more efficient. It is a variant of the AVL tree and Red-Black
tree.
- Splay Tree:
Key differences:
- Splay Trees are self-balancing, while Binary Trees can become unbalanced.
- Splay Trees have a dynamic root node, while Binary Trees have a fixed root.
- Splay Trees optimize search and access operations, while Binary Trees do
not.
- Splay: Rearrange the tree to move the accessed element to the root.
The Splay Tree’s self-balancing property and dynamic root node make it more
efficient for frequent search and access operations, especially in scenarios
with skewed access patterns.
Explain Quick sort algorithm. Sort the following set of data using this
algorithm. Show intermediate steps of sorting : 20, 6, 8, 19, 36, 4, 28, 50
(b) What is an Indexed Sequential File Organization ? How is it different from
direct file organisation ? Explain.
Steps:
2. Partition the array into two subarrays: elements less than the pivot and
elements greater than the pivot.
4. Combine the sorted subarrays and the pivot element to form the final
sorted array.
Key features:
Write Kruskal’s algorithm to find minimum cost spanning tree and explain it
in terms of its complexity.
A spanning tree of a graph is a subgraph that is a tree and contains all the
vertices of the original graph. It is a minimal connected subgraph that covers
all the nodes of the original graph.
Applications:
- Cluster analysis
- Data compression
Kruskal's Algorithm:
Complexity:
- Time: O(E log E) or O(E log V) using a priority queue.
Applications:
2. File system organization: AVL trees are used in file systems to manage file
metadata and directory structures.
Write algorithms for the following : (i) To create doubly linked list.
(ii) To delete an element from a doubly linked list. (b) What is a stack ?
Explain PUSH and POP operations of stack with the help of algorithms
for each operation.
(a) Algorithms:
(b)Stack:
PUSH Algorithm:
POP Algorithm:
Merge Step:
1. Initialize two pointers, one for each half.
2. Compare the elements at the pointers.
3. Take the smaller element and move the corresponding pointer.
4. Repeat until one half is exhausted.
5. Append the remaining elements from the other half.
Advantages:
Disadvantages:
Time Complexity:
Explanation:
Note: The 2-way Merge Sort is a popular sorting algorithm due to its
efficiency and stability. However, it may not be the best choice for
small datasets or nearly sorted data.
Write short notes on the following : (i) (ii) Sequential File Organization
Indexed Sequential File Organization
Here are brief notes on both:
the differences:
- Tree: A general data structure composed of nodes with child and parent
relationships.
- Binary Tree: A tree data structure with each node having at most two child
nodes (left and right).
- B-Tree: A multi-way search tree with data stored in both internal and leaf
nodes.
- B+-Tree: A variant of the B-Tree where data is stored only in leaf nodes, and
internal nodes contain only keys.
- Binary Tree: A tree with each node having at most two child nodes (left and
right).
- Binary Search Tree (BST): A binary tree with the property that the left
subtree of a node contains values less than the node, and the right subtree
contains values greater than the node.
In summary:
5. For any node, all paths from the node to its leaf nodes contain the
same number of black nodes (black height).
4. If the target value is less than the middle element, search the left
half.
5. If the target value is greater than the middle element, search the
right half.
6. Repeat steps 3-5 until the target value is found or the search space
is empty.
3. Repeat steps 1-2 for the remaining unsorted portion of the array.
1. Find the maximum element (65). Swap it with the last element (45).
2. Find the maximum element in the remaining array (50). Swap it with
the second-last element (18).
3. Repeat until the array is sorted in descending order: 65, 50, 45, 25,
21, 18, 10
``` +
/\
```
a -
/\
b c d
e f
/
g h
Compute the time complexity of Bubble Sort and Quick Sort algorithm.
Verify the statement “Best case for Bubble Sort is worst case for Quick
Sort”.
Time Complexity:
- Bubble Sort:
- Quick Sort:
The statement “Best case for Bubble Sort is worst case for Quick Sort”
is TRUE.
Bubble Sort’s best case (already sorted) has a time complexity of O(n),
which is the same as Quick Sort’s worst case (unbalanced partition)
time complexity.
In the best case for Bubble Sort, the algorithm only needs to traverse
the array once to confirm it’s sorted, resulting in O(n) time complexity.
However, in the worst case for Quick Sort, the partitioning process can
lead to very unbalanced subdivisions, resulting in a time complexity of
O(n^2), similar to Bubble Sort’s average and worst cases.
Write algorithm and Pseudo code for the following : (i) (ii) Inserting an
element in a doubly linked list. Deleting an element from a doubly
linked list.
Here are the algorithms and pseudo code for inserting and deleting
elements in a doubly linked list:
Algorithm:
2. If the list is empty, set the new node as the head and tail.
3. Otherwise, insert the new node at the beginning or end of the list,
depending on the desired position.
Pseudo code:
```
Procedure insertNode(element):
newNode ← CreateNode(element)
If list isEmpty:
Head ← newNode
Tail ← newNode
Else:
If insertAtBeginning:
newNode.next ← head
head.prev ← newNode
head ← newNode
Else:
newNode.prev ← tail
tail.next ← newNode
tail ← newNode
```
Algorithm:
2. If the node is found, update the previous and next nodes’ pointers.
3. If the node is the head or tail, update the head or tail pointer
accordingly.
Pseudo code:
```
Procedure deleteNode(element):
Node ← FindNode(element)
If node is found:
If node is head:
Head ← node.next
Else:
Node.prev.next ← node.next
If node is tail:
Tail ← node.prev
Else:
Node.next.prev ← node.prev
Free node
```
Note: The `FindNode` procedure is assumed to find the node with the
given element in the list.
- A node is inserted or deleted in the left subtree of the left child of the
root.
- The root is rotated to the right, and the left child becomes the new
root.
- The root is rotated to the left, and the right child becomes the new
root.
- The right child is rotated to the right, and then the root is rotated to
the left.
Write a program that accepts a matrix as input and prints the 3-tuple
representation of it.
What is Hashing ? Explain its use. Also, explain the concept of hashing
functions, with an example
```
def matrix_to_tuples(matrix):
tuples = []
for i in range(len(matrix)):
for j in range(len(matrix[i])):
tuples.append((i, j, matrix[i][j]))
return tuples
print(matrix_to_tuples(matrix))
```
Output: [(0, 0, 1), (0, 1, 2), (0, 2, 3), (1, 0, 4), (1, 1, 5), (1, 2, 6), (2, 0,
7), (2, 1, 8), (2, 2, 9)]
(c) Hashing
- Data compression
- Password storage
- Caching
Hashing Functions:
Input: 23
Hash code: 23 % 10 = 3
The hash code 3 indicates that the data corresponding to the key 23
should be stored at index 3 in the array.
Pseudo code:
```
Function isEmpty(stack):
If stack.top == NULL:
Return true
Else:
Return false
```
Red-Black Tree:
5. For any node, all paths from the node to its leaf nodes contain the
same number of black nodes (black height).
Define AVL Tree. Write the algorithm to insert a node into an AVL tree
and delete a node from an AVL tree.
AVL Tree:
Insertion Algorithm:
Pseudo code:
```
If root is NULL:
Else:
Else:
If balanceFactor > 1:
Return rightRotate(root)
Else:
Root.left = leftRotate(root.left)
Return rightRotate(root)
Return leftRotate(root)
Else:
Root.right = rightRotate(root.right)
Return leftRotate(root)
Return root
```
Deletion Algorithm:
Pseudo code:
```
If root is NULL:
Return root
Else:
Else:
If root.left is NULL:
Return root.right
Else:
If root.right is NULL:
Return root.left
Else:
Temp = minValueNode(root.right)
Root.key = temp.key
If balanceFactor > 1:
Return rightRotate(root)
Else:
Root.left = leftRotate(root.left)
Return rightRotate(root)
Return leftRotate(root)
Else:
Root.right = rightRotate(root.right)
Return leftRotate(root)
Return root
```
Write Pseudo code for Bubble Sort Algorithm. Sort the following list
using bubble sort in ascending order : 35, 39, 10, 8, 78, 92, 20, 50
Also, write the steps involved.
```
Procedure bubbleSort(arr):
N = length(arr)
For I = 0 to n-1:
For j = 0 to n-i-1:
```
3. If the first element is greater than the next element, swap them.
4. Move to the next element and repeat steps 2-3 until the end of the
array.
5. Repeat the process until no more swaps are needed, indicating that
the array is sorted.
Step 1:
List after first pass: 35, 10, 8, 39, 78, 20, 92, 50
Step 2:
List after second pass: 8, 10, 35, 39, 20, 78, 50, 92
Step 3:
List after third pass: 8, 10, 35, 20, 39, 50, 78, 92
Pseudo code:
```
Procedure enque(element):
If rear == size – 1:
Print “Queue is full”
Else:
Queue[rear] = element
Rear = (rear + 1) % size
Procedure deque():
If front == rear:
Print “Queue is empty”
Else:
Element = queue[front]
Front = (front + 1) % size
Return element
```
Pseudo code:
```
Procedure BFS(graph, start):
Queue = new Queue()
Queue.enque(start)
While queue is not empty:
Node = queue.deque()
Visit(node)
For each neighbor of node:
If neighbor is unvisited:
Queue.enque(neighbor)
```
Advantages:
Disadvantages:
- Difficult to implement
- Limited flexibility in file size
- Requires additional storage for block pointers