0% found this document useful (0 votes)
26 views45 pages

Mcs 21 Impquestion

Uploaded by

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

Mcs 21 Impquestion

Uploaded by

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

What is an algorithm ? What is complexity of an algorithm ?

Explain trade off


between space and time complexity with the help of an example.

(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)

- An algorithm is a well-defined procedure that takes some input and


produces a corresponding output. It is a step-by-step procedure for solving a
problem.

- The complexity of an algorithm refers to the amount of time and space it


requires as a function of the size of the input. Time complexity refers to the
number of steps an algorithm takes to complete, while space complexity
refers to the amount of memory used.

Trade-off between space and time complexity:

Example: Sorting a list of numbers

- Algorithm 1: Bubble sort (time complexity: O(n^2), space complexity: O(1))

- 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)

(i) Insert an element at the end of a linked list:


Algorithm:

1. Create a new node with the given element

2. If the list is empty, set the new node as the head

3. Otherwise, traverse the list to find the last node

4. Set the new node as the next node of the last node

5. Update the last node's next pointer to the new node

(ii) Delete an element from a linked list:

Algorithm:

1. Find the node to be deleted

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

4. Free the memory of the deleted 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.

(c) What is a circular queue ? Explain how it can be implemented using


arrays.

(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:

- Create an array of size `n` to store the queue elements.

- Initialize two pointers, `front` and `rear`, to 0.

- To enqueue an element, increment `rear` and store the element at the


calculated index `rear % n`.

- To dequeue an element, increment `front` and return the element at the


calculated index `front % n`.

- Check for queue full/empty conditions by comparing `front` and `rear`


indices.

(d) Prim's algorithm is a greedy algorithm used to find the Minimum Cost
Spanning Tree (MCST) of a weighted undirected graph.

Steps:

1. Choose an arbitrary node as the starting node.

2. Initialize a set `MST` to store the edges of the MCST.

3. While there are still nodes to be added to `MST`:

- Find the minimum-weight edge that connects a node in `MST` to a node


not in `MST`.

- Add this edge to `MST`.

- Add the new node to `MST`.

4. Return `MST` as the Minimum Cost Spanning Tree.

Explanation:
- Prim's algorithm starts with an arbitrary node and grows the MST by adding
nodes and edges greedily.

- At each step, it chooses the minimum-weight edge that connects a node in


the current MST to a node outside the MST.

- This ensures that the total weight of the MST is minimized.

- The algorithm terminates when all nodes are included in the MST.

Time complexity: O(|E|log|V|) using a priority queue.

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

Algorithm: Insertion Sort

Input: A list of numbers

Output: A sorted list of numbers

Step-by-Step Working:

1. Start with the first element (8)

2. Compare the next element (10) with the first element (8)

- Since 10 is greater than 8, move to the next element

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

- The list now is: 8, 8, 10, 25, 16, 27, 2, 45

5. Compare the next element (16) with the previous elements (8, 8, 10, 25)

- Since 16 is greater than 10, move to the next element

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)

- Since 2 is less than all previous elements, swap them

- The list now is: 2, 8, 8, 10, 16, 25, 27, 45

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

9. The list is now sorted: 2, 8, 8, 10, 16, 25, 27, 45

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

Here is the step-by-step construction of the AVL tree:

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.

Write an algorithm for adding two polynomials.

(b) Explain indexed sequential file organization with the help of an example.

(a) Algorithm for adding two polynomials:

Input: Two polynomials, P(x) and Q(x)

Output: The sum polynomial, R(x) = P(x) + Q(x)


Step-by-Step:

1. Initialize an empty polynomial, R(x)

2. Iterate through the terms of P(x) and Q(x)

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

R(x) = P(x) + Q(x) = (3+2)x^2 + (2-1)x + (1+4) = 5x^2 + x + 5

(b)Indexed Sequential File Organization:

Indexed sequential file organization is a method of storing and retrieving


data in a file. It combines the benefits of sequential and direct access file
organizations.

Example:

Suppose we have a file of student records with the following fields:

- Roll Number (unique)


- Name

- Marks

The file is organized as follows:

- The file is divided into fixed-size blocks or records

- Each block contains a fixed number of student records

- An index block contains pointers to the blocks where each student’s record
is stored

Index Block:

- Roll Number | Block Number

-1|1

-2|2

-3|1

-…

Data Blocks:

Block 1:

- Roll Number | Name | Marks

- 1 | John | 85

- 3 | Jane | 90

Block 2:

- Roll Number | Name | Marks


- 2 | Joe | 78

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.

What is a Red-Black tree ? Explain the properties of Red-Black tree. Explain


how a node is inserted in a Red-Black tree.

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:

A Red-Black tree is a self-balancing binary search tree with a guarantee of


O(log n) time for search, insert, and delete operations. It is a variation of the
B-Tree data structure and is commonly used in databases, file systems, and
other applications that require efficient storage and retrieval of data.

Properties of Red-Black Tree:

1. Each node is either red or black.

2. The root node is black.

3. All leaf nodes are black.

4. If a node is red, both its children must be black.


5. For any node, all paths from the node to its leaf nodes contain the same
number of black nodes (known as black height).

Insertion in Red-Black Tree:

1. Insert the new node as a red node.

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.

Algorithm for Binary Search:

Input: A sorted array, target value

Output: Index of the target value if found, -1 otherwise

Step-by-Step:

1. Find the middle index of the array.

2. Compare the target value with the middle element.

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:

- Finding a specific element in a sorted array or list.

- Determining whether a value is present in a sorted dataset.

- Finding the index of a value in a sorted array for efficient insertion or


deletion.

Breadth-First Search (BFS):

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.

Difference between BFS and Depth-First Search (DFS):

- BFS explores nodes level by level, while DFS explores nodes depth by
depth.

- BFS uses a queue, while DFS uses a stack.

- BFS is used for finding shortest paths and connected components, while
DFS is used for finding a path between two nodes and testing connectivity.

. (a) Write an algorithm for multiplication of two n × n matrices. Calculate


both time and space complexity for this algorithm.

b) What is a sparse matrix ? Write an algorithm that accepts a 6 × 5 sparse


matrix and output 3-tuple representation, of the matrix.

(a) Algorithm for Matrix Multiplication:


Input: Two n × n matrices, A and B

Output: Matrix C = A × B

Step-by-Step:

1. Initialize an n × n matrix C with all elements as 0.

2. For each element C[i][j]:

- Calculate the dot product of the i-th row of A and the j-th column of B.

- Store the result in C[i][j].

Time Complexity: O(n^3)

Space Complexity: O(n^2)

Explanation:

- Time complexity is O(n^3) because we have three nested loops (two for the
matrices and one for the dot product).

- Space complexity is O(n^2) because we need to store the resulting matrix


C.

(b)Sparse Matrix:

A sparse matrix is a matrix with a large number of zero elements. Storing


such a matrix in its entirety would be inefficient. Instead, we use a 3-tuple
representation (I, j, value) to store only the non-zero elements.
Algorithm for 3-tuple Representation:

Input: 6 × 5 sparse matrix

Output: 3-tuple representation of the matrix

Step-by-Step:

1. Initialize an empty list to store the 3-tuples.

2. Iterate through each element of the matrix:

- If the element is non-zero, add a 3-tuple (I, j, value) to the list.

3. Return the list of 3-tuples.

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)]
```

Write an algorithm for array implementation of linked list.

(d) What is a binary search ? Write an algorithm for binary search and find
its complexity.

Array Implementation of Linked List:

Algorithm:

1. Initialize an array `arr` of size `n` to store the linked list elements.

2. Initialize an array `next` of size `n` to store the next indices.

3. Set `next[0]` to `-1` (indicating the head of the list).

4. For each element `data` to be inserted:

- Find the first available index `i` in `arr` (where `next[i] == -1`).

- Set `arr[i]` to `data`.

- Set `next[i]` to the current `next` index (or `-1` if at the end).

- Update the `next` index.

5. To traverse the list:

- Start at index `0`.

- While `next[i] != -1`:

- Print `arr[i]`.

- Set `i` to `next[i]`.

Binary Search:
Binary search is an efficient algorithm for finding an element in a sorted
array.

Algorithm:

1. Sort the array if it's not already sorted.

2. Find the middle index `mid` of the array.

3. Compare the target element `target` to the middle element `arr[mid]`.

4. If `target == arr[mid]`, return `mid`.

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).

7. If the search space is empty, return `-1` (not found).

Complexity:

- Time complexity: O(log n) for a sorted array.

- Space complexity: O(1) since we only access elements in the array.

Note: The algorithm assumes a sorted array. If the array is not sorted, sorting
it first would add extra time complexity.

What is a Splay Tree ? Explain how is it different from a binary tree

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 vs Binary Tree:


- Binary Tree: A basic tree data structure with nodes having at most two
children (left and right).

- Splay Tree:

- A binary search tree with additional properties.

- Nodes are rearranged after search, insertion, or deletion operations to


move frequently accessed elements to the root.

- This rearrangement is called “splaying” and reduces the tree’s height.

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 Tree operations:

- Search: Find an element in the tree.

- Insert: Add a new element to the tree.

- Delete: Remove an element from the tree.

- 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.

(a) Quick Sort Algorithm:

Quick Sort is a divide-and-conquer algorithm that sorts an array of elements


by selecting a pivot element, partitioning the array around it, and recursively
sorting the subarrays.

Steps:

1. Choose a pivot element from the array.

2. Partition the array into two subarrays: elements less than the pivot and
elements greater than the pivot.

3. Recursively sort the subarrays.

4. Combine the sorted subarrays and the pivot element to form the final
sorted array.

Sorting the given data using Quick Sort:

Initial array: 20, 6, 8, 19, 36, 4, 28, 50

Step 1: Choose pivot (20)

Partition: <20 (6, 8, 4, 19) | >=20 (36, 28, 50)

Step 2: Recursively sort subarrays


<20: 4, 6, 8, 19

 =20: 28, 36, 50

Step 3: Combine sorted subarrays and pivot

Final sorted array: 4, 6, 8, 19, 20, 28, 36, 50

(b)Indexed Sequential File Organization:

Indexed Sequential File Organization is a file organization method that


combines the benefits of sequential and direct access file organizations. It
uses an index block to store pointers to the locations of records in the file,
allowing for efficient sequential access and direct access to specific records.

Difference from Direct File Organization:

Direct File Organization stores records in a contiguous block, allowing for


efficient direct access but slow sequential access. Indexed Sequential File
Organization stores records in a sequential manner but uses an index block
to facilitate direct access, making it more efficient for both sequential and
direct access.

Key features:

- Index block stores pointers to record locations

- Records are stored sequentially

- Supports efficient sequential access and direct access

- Useful for large files with frequent access and updates


What is a spanning tree ? What are its applications ?

Write Kruskal’s algorithm to find minimum cost spanning tree and explain it
in terms of its complexity.

Define AVL tree. Write any two applications of AVL tree.

(a) Spanning Tree:

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:

- Network design (e.g., telecommunications, transportation)

- Cluster analysis

- Data compression

Kruskal's Algorithm:

1. Sort all edges by weight in non-decreasing order.

2. Initialize an empty spanning tree.

3. Iterate through the sorted edges:

- If the edge connects two disconnected components, add it to the


spanning tree.

- Otherwise, skip it.

4. The resulting spanning tree is the minimum cost spanning tree.

Complexity:
- Time: O(E log E) or O(E log V) using a priority queue.

- Space: O(V + E) to store the graph and the spanning tree.

(b) AVL Tree:

An AVL tree is a self-balancing binary search tree that ensures efficient


search, insertion, and deletion operations. It was invented by Adelson-Velskii
and Landis in 1962.

Applications:

1. Database indexing: AVL trees are used in database indexing to efficiently


store and retrieve data.

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:

(i) Create Doubly Linked List:

1. Initialize head = NULL


2. For each element:
- Create a new node with the element
- Set next = head, prev = NULL
- If head != NULL, set head->prev = new node
- head = new node
(ii) Delete Element from Doubly Linked List:

1. Find the node to be deleted (node->data == target)


2. If node == head, set head = node->next
3. Else, set node->prev->next = node->next
4. If node->next != NULL, set node->next->prev = node->prev
5. Free the node

(b)Stack:

A stack is a Last-In-First-Out (LIFO) data structure that follows the


following operations:

PUSH Algorithm:

1. Create a new node with the element


2. Set top->next = new node
3. new node->prev = top
4. top = new node

POP Algorithm:

1. If stack is empty, return error


2. node = top
3. top = top->prev
4. Return node->data
5. Free the node

Write an algorithm of 2-way Merge Sort. Also discuss the advantage


and disadvantage of 2-way Merge Sort. Also calculate its time
complexity.
Algorithm:

1. Divide the array into two halves.


2. Recursively sort each half.
3. Merge the sorted halves into a single sorted array.

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:

- Stable sort (preserves order of equal elements)


- Efficient for large datasets
- Low memory overhead

Disadvantages:

- Recursive function calls can be expensive


- Not efficient for small datasets or nearly sorted data

Time Complexity:

- Best case: O(n log n)


- Average case: O(n log n)
- Worst case: O(n log n)

Explanation:

- Divide step takes O(log n) time.


- Recursively sorting each half takes O(n log n) time.
- Merge step takes O(n) time.
- Total time complexity is O(n log n) + O(log n) = O(n log n).

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:

*Sequential File Organization:*


- Records are stored in a contiguous block.
- Records are accessed in the order they are stored.
- Efficient for sequential access and batch processing.
- Inefficient for direct access and updating records.
- Example: A text file where each line is a record.

*Indexed Sequential File Organization:*

- Combines sequential storage with an index for direct access.


- Index contains pointers to record locations.
- Records are stored sequentially, but can be accessed directly using
the index.
- Efficient for both sequential and direct access.
- Example: A database table with an index on a specific column.

Differentiate between the following :


Heap and Tree
B-Tree and Binary Tree

B-Tree and B+-Tree

Binary Tree and Binary Search Tree

the differences:

(i) Heap and Tree:

- Heap: A specialized tree-based data structure that satisfies the heap


property (parent node is either greater than or equal to child nodes).

- Tree: A general data structure composed of nodes with child and parent
relationships.

(ii) B-Tree and Binary Tree:


- B-Tree: A self-balancing search tree with multiple child nodes (multi-way
search tree).

- Binary Tree: A tree data structure with each node having at most two child
nodes (left and right).

(iii) B-Tree and B+-Tree:

- 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.

(iv) Binary Tree and Binary Search Tree:

- 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:

- Heap is a specialized tree with a specific property.

- B-Tree is a self-balancing multi-way search tree.

- B+-Tree is a variant of B-Tree with data only in leaf nodes.

- Binary Tree is a general tree with at most two child nodes.

- Binary Search Tree is a binary tree with a specific ordering property.

What is a Red-Black tree ? Explain its properties.

Write an algorithm of Binary Search.


Write Selection Sort algorithm. Sort the following list using Selection
Sort in descending order : 25, 10, 50, 21, 65, 18, 45

Let ‘E’ denote the following algebraic expression : [a + (b – c)] * [(d –


e) / (f + g – h)] Draw the Binary tree for ‘E’.

(a) Red-Black Tree:

A Red-Black tree is a self-balancing binary search tree with the


following properties:

1. Each node is either red or black.

2. The root node is black.

3. All leaf nodes are black.

4. If a node is red, both its children must be black.

5. For any node, all paths from the node to its leaf nodes contain the
same number of black nodes (black height).

These properties ensure the tree remains approximately balanced,


allowing for efficient search, insertion, and deletion operations.

(b) Binary Search Algorithm:

1. Sort the array if it's not already sorted.

2. Find the middle index of the array.

3. Compare the target value to the middle element.

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.

(c) Selection Sort Algorithm:

1. Find the maximum element in the array.

2. Swap it with the last element.

3. Repeat steps 1-2 for the remaining unsorted portion of the array.

Sorting the list in descending order using Selection Sort:

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

(d) Binary Tree for Algebraic Expression 'E':

``` +

/\

```

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:

- Best case: O(n) (already sorted)

- Average case: O(n^2)

- Worst case: O(n^2)

- Quick Sort:

- Best case: O(n log n) (balanced partition)

- Average case: O(n log n)

- Worst case: O(n^2) (unbalanced partition)

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:

(i) Inserting an element in a doubly linked list:

Algorithm:

1. Create a new node with the given element.

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

```

(ii) Deleting an element from a doubly linked list:

Algorithm:

1. Find the node to be deleted.

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.

What is AVL Tree ? Discuss the mechanism of the following rotations


used in AVL tree : (i) (ii) LL LR (iii) RR (iv) RL

An AVL tree is a self-balancing binary search tree that ensures efficient


search, insertion, and deletion operations. It was invented by Adelson-
Velskii and Landis in 1962.

The AVL tree uses rotations to maintain balance when inserting or


deleting nodes. There are four types of rotations:

(i) LL Rotation (Left-Left):

- 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.

(ii) LR Rotation (Left-Right):

- A node is inserted or deleted in the right subtree of the left child of


the root.
- The left child is rotated to the left, and then the root is rotated to the
right.

(iii) RR Rotation (Right-Right):

- A node is inserted or deleted in the right subtree of the right child of


the root.

- The root is rotated to the left, and the right child becomes the new
root.

(iv) RL Rotation (Right-Left):

- A node is inserted or deleted in the left subtree of the right child of


the root.

- The right child is rotated to the right, and then the root is rotated to
the left.

These rotations maintain the balance property of the AVL tree,


ensuring that the height of the tree remains relatively small, which
leads to efficient search and insertion operations.

Write a program that accepts a matrix as input and prints the 3-tuple
representation of it.

Explain the organization. Index sequential file

What is Hashing ? Explain its use. Also, explain the concept of hashing
functions, with an example

(a) Program to print 3-tuple representation of a matrix:

```

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

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

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)]

(b) Organization: Index Sequential File

An index sequential file is a data storage method that combines the


benefits of sequential and direct access files. It uses an index block to
store pointers to the locations of records in the file, allowing for
efficient sequential access and direct access to specific records.

(c) Hashing

Hashing is a technique used for storing and retrieving data efficiently.


It involves mapping a large dataset to a smaller dataset using a hash
function. The hash function takes a key as input and generates a hash
code, which is used to index the data.

Hashing is used in various applications, such as:


- Data retrieval

- Data compression

- Password storage

- Caching

Hashing Functions:

A hashing function is a mathematical function that takes a variable-


length input and returns a fixed-length output. The output is known as
the hash code or digest.

Example: Modulo Hash Function

Suppose we have a dataset of integers and want to store them in an


array of size 10. We can use the modulo hash function to map the
integers to indices in the array.

Hash function: h(x) = x % 10

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.

Write an algorithm to check whether stack is empty or not.

Describe Big ‘O’ and omega notations.

What is Red-Black Tree ? Explain the properties of Red-Black Tree.


(a) Algorithm to check if a stack is empty:

1. If the stack's top pointer is NULL, the stack is empty.

2. Return true if the stack is empty, false otherwise.

Pseudo code:

```

Function isEmpty(stack):

If stack.top == NULL:

Return true

Else:

Return false

```

(b) Big O notation:

Big O notation represents the upper bound of an algorithm's time or


space complexity. It measures the worst-case scenario, providing an
estimate of how long an algorithm takes to complete as the input size
grows.

Example: Bubble sort has a time complexity of O(n^2), where n is the


number of elements in the array.

(c) Big Ω (Omega) notation:


Big Ω notation represents the lower bound of an algorithm's time or
space complexity. It measures the best-case scenario, providing an
estimate of how long an algorithm takes to complete as the input size
grows.

Example: Bubble sort has a time complexity of Ω(n), where n is the


number of elements in the array (when the array is already sorted).

Red-Black Tree:

A Red-Black Tree is a self-balancing binary search tree with the


following properties:

1. Each node is either red or black.

2. The root node is black.

3. All leaf nodes are black.

4. If a node is red, both its children must be black.

5. For any node, all paths from the node to its leaf nodes contain the
same number of black nodes (black height).

These properties ensure the tree remains approximately balanced,


allowing for efficient search, insertion, and deletion operations.

Define AVL Tree. Write the algorithm to insert a node into an AVL tree
and delete a node from an AVL tree.

AVL Tree:

An AVL tree is a self-balancing binary search tree that ensures efficient


search, insertion, and deletion operations. It was invented by Adelson-
Velskii and Landis in 1962. The tree is named after its creators and is a
type of binary search tree that automatically balances itself after
insertion or deletion of nodes.

Insertion Algorithm:

1. Perform a standard binary search tree insertion.

2. If the balance factor of the tree becomes unbalanced (greater than


1 or less than -1), perform rotations to balance the tree.

Pseudo code:

```

Function insertNode(root, key):

If root is NULL:

Return a new node with key

Else:

If key < root.key:

Root.left = insertNode(root.left, key)

Else:

Root.right = insertNode(root.right, key)

balanceFactor = height(root.left) – height(root.right)

If balanceFactor > 1:

If key < root.left.key:

Return rightRotate(root)

Else:
Root.left = leftRotate(root.left)

Return rightRotate(root)

If balanceFactor < -1:

If key > root.right.key:

Return leftRotate(root)

Else:

Root.right = rightRotate(root.right)

Return leftRotate(root)

Return root

```

Deletion Algorithm:

1. Perform a standard binary search tree deletion.

2. If the balance factor of the tree becomes unbalanced (greater than


1 or less than -1), perform rotations to balance the tree.

Pseudo code:

```

Function deleteNode(root, key):

If root is NULL:

Return root

Else:

If key < root.key:

Root.left = deleteNode(root.left, key)


Else:

If key > root.key:

Root.right = deleteNode(root.right, key)

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

Root.right = deleteNode(root.right, temp.key)

balanceFactor = height(root.left) – height(root.right)

If balanceFactor > 1:

If height(root.left.left) >= height(root.left.right):

Return rightRotate(root)

Else:

Root.left = leftRotate(root.left)

Return rightRotate(root)

If balanceFactor < -1:

If height(root.right.right) >= height(root.right.left):

Return leftRotate(root)

Else:

Root.right = rightRotate(root.right)
Return leftRotate(root)

Return root

```

Note: The `leftRotate` and `rightRotate` functions perform the


necessary rotations to balance the tree. The `height` function
calculates the height of the tree, and the `minValueNode` function
finds the node with the minimum value in the tree.

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.

Pseudo code for Bubble Sort Algorithm:

```

Procedure bubbleSort(arr):

N = length(arr)

For I = 0 to n-1:

For j = 0 to n-i-1:

If arr[j] > arr[j+1]:

Swap arr[j] and arr[j+1]

```

Steps involved in Bubble Sort:

1. Start with the first element of the array.

2. Compare it with the next element.

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.

Sorting the list using Bubble Sort in ascending order:

List: 35, 39, 10, 8, 78, 92, 20, 50

Step 1:

Compare 35 and 39: no swap needed

Compare 39 and 10: swap

Compare 10 and 8: swap

Compare 8 and 78: no swap needed

Compare 78 and 92: no swap needed

Compare 92 and 20: swap

Compare 20 and 50: no swap needed

List after first pass: 35, 10, 8, 39, 78, 20, 92, 50

Step 2:

Compare 35 and 10: swap

Compare 10 and 8: swap

Compare 8 and 39: no swap needed

Compare 39 and 78: no swap needed

Compare 78 and 20: swap

Compare 20 and 92: no swap needed


Compare 92 and 50: no swap needed

List after second pass: 8, 10, 35, 39, 20, 78, 50, 92

Step 3:

Compare 8 and 10: no swap needed

Compare 10 and 35: no swap needed

Compare 35 and 39: no swap needed

Compare 39 and 20: swap

Compare 20 and 78: no swap needed

Compare 78 and 50: no swap needed

Compare 50 and 92: no swap needed

List after third pass: 8, 10, 35, 20, 39, 50, 78, 92

No more swaps are needed, so the list is sorted in ascending order: 8,


10, 20, 35, 39, 50, 78, 92

a) What is Circular Queue ? Write an algorithm to add an element and


delete an element in a circular queue. (b) (c) Write Breadth-first
search algorithm. Explain Direct File Organisation.

(a) Circular Queue:

A circular queue is a type of queue where the last element points


back to the first element, forming a circle. It’s a data structure that
uses an array to store elements, and the indices are modulo the
size of the array.

Algorithm to add an element (enque):

1. Check if the queue is full (rear == size – 1)


2. If full, print error message and return
3. Else, add element to the rear index
4. Increment rear index modulo size

Algorithm to delete an element (deque):

1. Check if the queue is empty (front == rear)


2. If empty, print error message and return
3. Else, remove element from the front index
4. Increment front index modulo size

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
```

(b)Breadth-First Search (BFS) Algorithm:

BFS is a graph traversal algorithm that explores all nodes at the


current level before moving to the next level.

1. Create a queue to hold nodes to visit


2. Enque the starting node
3. While the queue is not empty:
- Deque a node
- Visit the node (process it)
- Enque all unvisited neighbors of the node
4. Repeat step 3 until the queue is empty

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)
```

© Direct File Organization:

Direct file organization is a method of storing files on a disk where


each file is stored in a contiguous block of space. The file is divided
into fixed-size blocks, and each block contains a pointer to the next
block in the file.

Advantages:

- Efficient use of storage space


- Fast access to files
- Reduced fragmentation

Disadvantages:

- Difficult to implement
- Limited flexibility in file size
- Requires additional storage for block pointers

You might also like