0% found this document useful (0 votes)
92 views

Define Data Structure 2023 Question Paper With Solution

The document discusses data structures and their operations. It provides definitions and examples of common data structures like arrays, queues, trees and B-trees. For each question, it explains concepts such as abstract data types, different traversal methods for trees and operations for priority queues and B-trees.

Uploaded by

Brijesh C.G
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views

Define Data Structure 2023 Question Paper With Solution

The document discusses data structures and their operations. It provides definitions and examples of common data structures like arrays, queues, trees and B-trees. For each question, it explains concepts such as abstract data types, different traversal methods for trees and operations for priority queues and B-trees.

Uploaded by

Brijesh C.G
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Assistant professor. 3rd Semester B.C.

A Degree Examination, January-2024


Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

Answer any four questions. Each question carries 2 marks :


1. Define data structure. List out any two operations of data structure.
A data structure is a specialized format for organizing, storing, and manipulating data in a
computer's memory. It enables efficient access and modification of data by providing a systematic
arrangement of elements with well-defined relationships between them. Data structures are
essential components of computer programs and are used to solve various computational problems.

Two common operations of data structures are:

1. Insertion: This operation involves adding a new element to the data structure at a specific position.
Insertion can be performed in different data structures like arrays, linked lists, trees, and hash tables.

2. Deletion: This operation involves removing an existing element from the data structure. Deletion
can also be performed in various data structures such as arrays, linked lists, trees, and hash tables.
The process of deletion may involve reorganizing the remaining elements to maintain the structure's
integrity.

2. Write ADT of an array.


An Abstract Data Type (ADT) is a high-level description of a collection of data and the
operations that can be performed on that data. It defines the behavior and structure of the
data type but does not provide implementation details. Here is the ADT of an array:

Array ADT:

1. Data:
- A collection of elements, where each element is stored at a specific index.
- The size of the array, which represents the total number of elements it can store.
- The length of the array, which is the current number of elements in the array.

2. Operations:
- Create(size): Create a new array with the specified size.
- Get(index): Retrieve the element at the specified index in the array.
- Set(index, value): Update the element at the specified index with the given value.
- Insert(index, value): Insert a new element with the given value at the specified index. This
may involve shifting elements to make room for the new value.
- Delete(index): Remove the element at the specified index from the array. This may involve
shifting elements to fill the gap created by the deletion.
- Length(): Return the current length of the array (i.e., the number of elements in the
array).
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

- Resize(newSize): Change the size of the array to the specified newSize, which can be
larger or smaller than the current size. This may involve allocating new memory or
deallocating unused memory.
- Traverse(): Perform an operation on each element in the array, such as printing or
processing the elements.
- Search(value): Find the index of the first occurrence of a given value in the array, or return
-1 if the value is not found.

Note that the specific implementation of these operations may vary depending on the
programming language or data structure library being used.

3. What is queue ? And mention its types.


A queue is a linear data structure that follows the First-In-First-Out (FIFO) principle,
meaning that the first element added to the queue will be the first one to be removed. It
operates like a real-life queue, such as a line of people waiting at a bus stop or a ticket
counter. Elements are inserted (enqueued) at the rear (end) of the queue and removed
(dequeued) from the front (beginning) of the queue.

There are two main types of queues:

1. Simple Queue (also known as a Sequential Queue):

Diagram:

Front -> | 10 | 20 | 30 | 40 | <- Rear

A simple queue has two pointers, front and rear, to indicate the beginning and end of the
queue. Elements are enqueued at the rear and dequeued from the front. Once the front
reaches the end of the queue's capacity, even if there are empty spaces in the front, it
cannot insert more elements unless the entire queue is shifted.

2. Circular Queue:

Diagram:

Front -> | 30 | 40 | 10 | 20 | <- Rear

A circular queue is an improvement over a simple queue. It treats the front and rear as
adjacent, allowing the rear pointer to wrap around to the beginning when it reaches the end
of the queue's capacity. This eliminates the need for shifting elements and makes better use
of available space.

There are also variations of these basic queue types, such as:

1. Priority Queue:
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

Elements in a priority queue are assigned a priority, and elements with higher priority are
dequeued before elements with lower priority.

2. Deque (Double-ended Queue):


A deque allows elements to be inserted and removed from both the front and rear,
providing more flexibility in element manipulation.

3. Multilevel Queue:
A multilevel queue consists of multiple simple or circular queues, each with its own priority
or purpose. Elements are enqueued and dequeued based on the priority of their respective
queues.

4. Mention the different ways of tree traversal.


Tree traversal is the process of visiting each node in a tree data structure, such as a binary
tree, in a systematic manner. There are three primary methods of tree traversal, each of
which can be performed in two orders: depth-first and breadth-first.

Depth-First Traversal:

1. Preorder Traversal (Root, Left, Right):


In this traversal method, the root node is visited first, followed by its left subtree, and
finally, its right subtree.

2. Inorder Traversal (Left, Root, Right):


In this traversal method, the left subtree is visited first, followed by the root node, and
finally, its right subtree. In the case of a binary search tree, inorder traversal results in a
sorted list of node values.

3. Postorder Traversal (Left, Right, Root):


In this traversal method, the left subtree is visited first, followed by the right subtree, and
finally, the root node.

Breadth-First Traversal (also called Level-Order Traversal):

4. Level-Order Traversal:
In level-order traversal, nodes are visited level by level, starting from the root. Nodes in the
same level are visited from left to right. This traversal method uses a queue to keep track of
the nodes at each level.

These traversal methods are mainly used for searching, inserting, or deleting nodes in a tree,
as well as for other operations like printing the tree nodes in a specific order. Each traversal
method has its own use case and can be applied depending on the specific requirements of a
problem or algorithm.

5. What is'B'Tree ? Mention its operation.


Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

A B-Tree (short for Balanced Tree) is a self-balancing tree data structure that
maintains a sorted order of its elements and allows for efficient insertion, deletion,
and search operations. B-Trees are commonly used in database systems and file
systems to organize and manage large amounts of data.

A B-Tree has the following properties:

1. Each node in the B-Tree contains a certain number of keys (elements) and child
pointers, with the keys sorted in ascending order.
2. All the leaves (nodes with no children) appear at the same level, ensuring that the
tree remains balanced.
3. A B-Tree has a minimum degree 't' (t ≥ 2), which determines the minimum and
maximum number of keys and children a node can have:
- Every node, except the root, must have at least (t - 1) keys and t children.
- Every node can have at most (2t - 1) keys and 2t children.
- The root node can have a minimum of 1 key and a maximum of (2t - 1) keys.

Operations on a B-Tree:

1. Search: Searches for a specific key in the B-Tree by traversing the tree from the
root to the appropriate leaf node based on the key's value. The search operation
takes O(log n) time complexity.

2. Insert: Inserts a new key into the B-Tree while maintaining the tree's properties. If
the node where the key should be inserted becomes full (has 2t - 1 keys), the node is
split, and the middle key is moved up to the parent node. This process may be
repeated up to the root node. The insert operation takes O(log n) time complexity.

3. Delete: Removes a key from the B-Tree while maintaining the tree's properties.
Depending on the key's location, the delete operation may involve redistributing keys
or merging nodes to ensure that all nodes (except the root) have at least (t - 1) keys.
The delete operation takes O(log n) time complexity.

4. Traverse: Visits all the keys in the B-Tree in a sorted order, typically using an
inorder traversal method.

B-Trees are particularly useful in situations where the data is too large to fit in main
memory and needs to be stored on secondary storage devices (e.g., hard disks). Their
balanced structure and efficient operations help minimize disk I/O operations and
provide fast access to the stored data.
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

6. Define any two collision resolution in Hashing.


Collision resolution in hashing refers to the process of handling
situations where two or more keys have the same hash value (i.e., a
collision occurs). There are several techniques for resolving collisions in
hash tables. Here are two common methods:

1. Separate Chaining (also called Open Hashing):

In separate chaining, each slot in the hash table contains a linked list (or
another data structure) to store the keys that collide with each other.
When a collision occurs, the new key is simply added to the linked list at
the appropriate slot.

To search for a key in the hash table, the hash function is applied to the
key to determine the slot, and then the linked list at that slot is traversed
to find the desired key.

Pros:
- It can handle an arbitrary number of collisions per slot.
- The load factor can exceed 1, meaning the number of keys can be
greater than the size of the hash table.

Cons:
- The performance can degrade if the linked lists become too long, as
searching through the list takes linear time.
- It requires additional memory to store the linked lists.

2. Open Addressing (also called Closed Hashing):

In open addressing, all keys are stored directly in the hash table itself,
and collisions are resolved by finding another available slot in the table.
When a collision occurs, a probing sequence is used to determine the
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

next available slot. There are several probing techniques, such as linear
probing, quadratic probing, and double hashing.

- Linear Probing: When a collision occurs, the next available slot is


searched sequentially (linearly) until an empty slot is found.
- Quadratic Probing: When a collision occurs, the next available slot is
searched using a quadratic function, i.e., incrementing the search index
by the square of the probe number.
- Double Hashing: When a collision occurs, a secondary hash function is
used to determine the next available slot.

Pros:
- It does not require additional memory to store linked lists or other data
structures.
- It can provide better cache performance since all keys are stored in the
hash table itself.

Cons:
- The load factor should be kept below 1 to ensure that an empty slot
can always be found.
- The performance can degrade if the hash table becomes too full, as the
probing sequence may need to search through many slots to find an
available slot or the desired key.

Both separate chaining and open addressing have their advantages and
disadvantages, and the choice of collision resolution technique depends
on the specific requirements of the application and the expected
distribution of keys.
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

SECTION _ B
Answer any four questions. Each question carries 5 marks.

7. what is algorithm ? Explain time and space complexity of algorithm.


An algorithm is a step-by-step procedure or a set of instructions for
solving a specific problem or performing a particular task. It is a well-defined,
finite sequence of operations designed to process input data and produce a
desired output. Algorithms are the foundation of computer programs and are
used to solve various computational problems efficiently and effectively.

Time Complexity:

Time complexity is a measure of the amount of time an algorithm takes to run


as a function of the input size. It is an estimation of the number of basic
operations (such as additions, multiplications, comparisons, etc.) an algorithm
performs during its execution. Time complexity is used to compare the
efficiency of different algorithms for the same problem or task, with lower time
complexity generally indicating a more efficient algorithm.

Time complexity is often expressed using big O notation, which describes the
upper bound of an algorithm's growth rate. For example, O(n) represents linear
time complexity, meaning the algorithm's running time increases linearly with
the input size, while O(n^2) represents quadratic time complexity, meaning the
running time increases quadratically with the input size.

Space Complexity:

Space complexity is a measure of the amount of memory an algorithm uses as


a function of the input size. It is an estimation of the total storage space
required by the algorithm, including the input data, any additional data
structures, and the output. Space complexity is used to compare the memory
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

efficiency of different algorithms for the same problem or task, with lower
space complexity generally indicating a more memory-efficient algorithm.

Space complexity is also often expressed using big O notation, which describes
the upper bound of an algorithm's memory usage. For example, O(1)
represents constant space complexity, meaning the algorithm uses a fixed
amount of memory regardless of the input size, while O(n) represents linear
space complexity, meaning the algorithm's memory usage increases linearly
with the input size.

In summary, an algorithm is a set of instructions for solving a problem or


performing a task. Time complexity and space complexity are measures used to
evaluate and compare the efficiency of algorithms in terms of their running
time and memory usage, respectively.

8. Write an algorithm to delete a node in the queue.


Deleting a node in a queue typically means removing the element from the
front of the queue, following the First-In-First-Out (FIFO) principle. Here's an
algorithm for deleting a node from a queue:
1. Check if the queue is empty:
1.1. If the queue is empty, print "Queue is empty, cannot delete a node" and
terminate the algorithm.
2. Save the value of the front element in a temporary variable, e.g., temp =
queue[front].
3. Increment the front pointer: front = front + 1.
4. If the front pointer is equal to the queue size (front == size), reset the front
pointer to 0, making the queue empty.
5. Return the value of the deleted node (temp).
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

Please note that this algorithm assumes the implementation of a simple


(sequential) queue using an array and front and rear pointers to represent the
queue's beginning and end. If a different implementation, such as a circular
queue or a linked list, is used, the algorithm for deleting a node may vary
slightly. Also, this algorithm does not handle dynamic resizing of the queue,
which may be necessary in some cases to optimize memory usage.

9. Evaluate the following infix to prefix Q=(A+B) /(C*D).


To convert an infix expression to prefix notation, you can follow these steps:

1. Reverse the infix expression (from left to right).


2. Replace '(' with ')' and ')' with '(' in the reversed expression.
3. Convert the modified expression to postfix notation.
4. Reverse the postfix expression to obtain the prefix expression.

Here's the conversion for the given infix expression Q = (A + B) / (C * D):

1. Reverse the infix expression: .D*C/)+B(A=


2. Replace the brackets: =D*C\)+B(A)
3. Convert to postfix notation (using the modified expression and following the usual
postfix conversion rules):
=D C * B A + )(
=D C * B A + / Q
4. Reverse the postfix expression: Q / + A B * C D

So, the prefix notation for the given infix expression is: Q/+AB*CD

10. Explain AVL tree with its operation


An AVL tree (Adelson-Velsky and Landis tree) is a self-balancing binary
search tree (BST) that automatically adjusts its height after any insertion or deletion
of nodes to maintain a balanced structure. It was named after its inventors, G.M.
Adelson-Velsky and E.M. Landis. The key property of an AVL tree is that the heights of
the left and right subtrees of any node differ by at most 1. This ensures that the tree
remains approximately balanced, resulting in logarithmic time complexity for most
operations.

Operations on AVL trees:

1. Search: Searching in an AVL tree is the same as searching in a regular binary search
tree. Starting from the root, the search compares the target value with the current
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

node's value and moves left or right based on the comparison. The search operation
has a time complexity of O(log n) due to the balanced nature of the AVL tree.

2. Insertion: When inserting a new node into an AVL tree, the process starts by
inserting the node as in a regular binary search tree. After the insertion, the tree's
balance may be violated, so the tree needs to be rebalanced. This rebalancing is
done using rotations:

- Single rotation (left or right): If the balance is disturbed in one direction (left or
right), a single rotation can be used to restore balance.
- Double rotation (left-right or right-left): If the balance is disturbed in a zigzag
pattern, a double rotation is required to restore balance.

The insertion operation has a time complexity of O(log n), which includes both the
initial insertion and the rebalancing process.

3. Deletion: Deleting a node from an AVL tree involves finding the node, removing it
as in a regular binary search tree, and then rebalancing the tree if necessary. Similar
to insertion, the rebalancing process may involve single or double rotations. The
deletion operation has a time complexity of O(log n).

4. Traversal: AVL trees can be traversed using various tree traversal techniques, such
as inorder, preorder, and postorder traversal. The traversal operation has a time
complexity of O(n) as it visits all n nodes in the tree.

In summary, an AVL tree is a self-balancing binary search tree that ensures


logarithmic time complexity for most operations by maintaining a balanced structure
through rotations. The primary operations on an AVL tree include search, insertion,
deletion, and traversal.

11. Explain DFS algorithm through stack concept.

The depth-first search or DFS algorithm traverses or explores data structures, such
as trees and graphs. The algorithm starts at the root node (in the case of a graph, you can use
any random node as the root node) and examines each branch as far as possible before
backtracking.
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

When a dead-end occurs in any iteration, the Depth First Search (DFS) method traverses a
network in a deathward motion and uses a stack data structure to remember to acquire the
next vertex to start a search.

The outcome of a DFS traversal of a graph is a spanning tree. A spanning tree is a graph that
is devoid of loops. To implement DFS traversal, you need to utilize a stack data structure
with a maximum size equal to the total number of vertices in the graph.

To implement DFS traversal, you need to take the following stages.

Step 1: Create a stack with the total number of vertices in the graph as the size.

Step 2: Choose any vertex as the traversal's beginning point. Push a visit to that vertex and
add it to the stack.

Step 3 - Push any non-visited adjacent vertices of a vertex at the top of the stack to the top of
the stack.

Step 4 - Repeat steps 3 and 4 until there are no more vertices to visit from the vertex at the
top of the stack.

Step 5 - If there are no new vertices to visit, go back and pop one from the stack using
backtracking.
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

Step 6 - Continue using steps 3, 4, and 5 until the stack is empty.

Step 7 - When the stack is entirely unoccupied, create the final spanning tree by deleting the
graph's unused edges.

Consider the following graph as an example of how to use the dfs algorithm.

Step 1: Mark vertex A as a visited source node by selecting it as a source node.

 You should push vertex A to the top of the stack.


Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

Step 2: Any nearby unvisited vertex of vertex A, say B, should be visited.

 You should push vertex B to the top of the stack.

Step 3: From vertex C and D, visit any adjacent unvisited vertices of vertex B. Imagine you
have chosen vertex C, and you want to make C a visited vertex.
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

 Vertex C is pushed to the top of the stack.

Step 4: You can visit any nearby unvisited vertices of vertex C, you need to select vertex D
and designate it as a visited vertex.

 Vertex D is pushed to the top of the stack.


Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

Step 5: Vertex E is the lone unvisited adjacent vertex of vertex D, thus marking it as visited.

 Vertex E should be pushed to the top of the stack.

Step 6: Vertex E's nearby vertices, namely vertex C and D have been visited, pop vertex E
from the stack.
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

Step 7: Now that all of vertex D's nearby vertices, namely vertex B and C, have been visited,
pop vertex D from the stack.

Step 8: Similarly, vertex C's adjacent vertices have already been visited; therefore, pop it
from the stack.
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

Step 9: There is no more unvisited adjacent vertex of b, thus pop it from the stack.

Step 10: All of the nearby vertices of Vertex A, B, and C, have already been visited, so pop
vertex A from the stack as well.
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

12 Explain quick sort algorithm.


The key process in quickSort is a partition(). The target of partitions is
to place the pivot (any element can be chosen to be a pivot) at its correct
position in the sorted array and put all smaller elements to the left of the
pivot, and all greater elements to the right of the pivot.
Partition is done recursively on each side of the pivot after the pivot is
placed in its correct position and this finally sorts the array.

The logic is simple, we start from the leftmost element and keep track of
the index of smaller (or equal) elements as i. While traversing, if we find
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

a smaller element, we swap the current element with arr[i]. Otherwise,


we ignore the current element.

Consider: arr[] = {10, 80, 30, 90, 40}.


 Compare 10 with the pivot and as it is less than pivot arrange it
accrodingly.

 Compare 80 with the pivot. It is greater than pivot.

 Compare 30 with pivot. It is less than pivot so arrange it accordingly.

 Compare 90 with the pivot. It is greater than the pivot.


Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

 Arrange the pivot in its correct position.

Answer any four questions. Each question carries 8 marks :

12. A. Explain Asymptotic notation with example.


b. Write the 'C' program to display sparse matrix
and its transpose.
a.Asymptotic notation is a way to describe the growth of a function, typically used
in computer science and mathematics for analyzing the efficiency of algorithms. It
provides an approximation of a function's behavior as its input grows towards
infinity, allowing us to compare and classify algorithms based on their running time
or space complexity. The three most common types of asymptotic notation are big O
notation (O), big Omega notation (Ω), and big Theta notation (Θ).

1. Big O notation (O): This notation represents the upper bound of a function,
which means it describes the maximum growth rate of the function. It is used to give
an upper limit on the running time of an algorithm in the worst case, thus providing
a guarantee that the algorithm will not perform worse than the given big O
notation. Example: The time complexity of a linear search algorithm is O(n), which
means that the time it takes to search for an element in a list grows linearly with the
size of the list.

2. Big Omega notation (Ω): This notation represents the lower bound of a function,
which means it describes the minimum growth rate of the function. It is used to give
a lower limit on the running time of an algorithm in the best case, thus providing a
guarantee that the algorithm will not perform better than the given big Omega
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

notation. Example: The time complexity of a binary search algorithm is Ω(log n),
which means that the time it takes to search for an element in a sorted list grows
logarithmically with the size of the list.

3. Big Theta notation (Θ): This notation represents the tight bound of a function,
which means it describes the exact growth rate of the function. It is used when the
algorithm's growth rate is both upper and lower bounded by the same function, thus
providing an accurate estimate of the algorithm's efficiency. Example: The time
complexity of the merge sort algorithm is Θ(n log n), which means that the time it
takes to sort a list grows linearithmically (linearly and logarithmically) with the
size of the list.
In summary, asymptotic notation helps us describe and compare the growth rates of
functions, which is especially useful for analyzing the efficiency of algorithms in
terms of their running time or space complexity.

s
A sparse matrix is a matrix in which the majority of its elements are zero. Here's a
C program to display a sparse matrix and its transpose:

#include <stdio.h>

int main() {

int m, n, count = 0;

printf("Enter the dimensions of the matrix (m x n): ");

scanf("%d %d", &m, &n);

int matrix[m][n];

printf("Enter the elements of the matrix:\n");

for (int i = 0; i < m; i++) {

for (int j = 0; j < n; j++) {

scanf("%d", &matrix[i][j]);

if (matrix[i][j] != 0) {

count++;

}
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

int sparse[count][3], k = 0;

for (int i = 0; i < m; i++) {

for (int j = 0; j < n; j++) {

if (matrix[i][j] != 0) {

sparse[k][0] = i;

sparse[k][1] = j;

sparse[k][2] = matrix[i][j];

k++;

printf("Sparse Matrix:\n");

for (int i = 0; i < count; i++) {

for (int j = 0; j < 3; j++) {

printf("%d ", sparse[i][j]);

printf("\n");

int transpose[count][3];

for (int i = 0; i < count; i++) {


Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

transpose[i][0] = sparse[i][1];

transpose[i][1] = sparse[i][0];

transpose[i][2] = sparse[i][2];

printf("Transpose of the Sparse Matrix:\n");

for (int i = 0; i < count; i++) {

for (int j = 0; j < 3; j++) {

printf("%d ", transpose[i][j]);

printf("\n");

return 0;

```

This program first reads the dimensions and elements of a matrix, then converts it
into a sparse matrix representation (using a 2D array with three columns: row,
column, and value). It then calculates the transpose of the sparse matrix by
swapping the row and column values and displays both the sparse matrix and its
transpose.

14.a. ) Explain array concepts with its classification.


b. Write an algorithm to insert an element to the given
array A = {10, 30, 40, 50}. lnsert element 2A at the position
2.

a.solution.
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

An array is a data structure that consists of a collection of elements, each


identified by an index or a key. The elements in an array are stored in contiguous
memory locations, making it easy to access and manipulate them. Arrays are
useful for storing and organizing data when the number of elements and their
positions are known in advance.

The main concepts associated with arrays are:

1. Element: An individual item stored in an array. Elements can be of any data


type, such as integers, floating-point numbers, characters, or even other arrays (in
the case of multidimensional arrays).

2. Index: A unique identifier associated with each element in the array. In most
programming languages, indices start from 0, meaning that the first element has
an index of 0, the second element has an index of 1, and so on.

3. Length or size: The total number of elements in the array. The length is a fixed
property of the array and cannot be changed once the array is created.

4. Memory allocation: Arrays are stored in contiguous memory locations, which


means that the elements are stored next to each other in memory. This allows for
efficient access and manipulation of elements using their indices.

Arrays can be classified based on their dimensions and the type of elements they
store:

1. One-dimensional arrays (1D arrays): These are simple, linear arrays that
contain a single row or column of elements. Each element in a 1D array can be
accessed using a single index.

Example: int arr[5] = {1, 2, 3, 4, 5};

2. Multidimensional arrays: These are arrays that contain more than one row or
column of elements. They can be thought of as arrays of arrays. The most
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

common type of multidimensional array is a two-dimensional array (2D array),


which consists of rows and columns, similar to a matrix. Elements in a
multidimensional array can be accessed using multiple indices, one for each
dimension.

Example: int matrix[3][4] = {


{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};

3. Homogeneous arrays: These are arrays that store elements of the same data
type. All elements in a homogeneous array must be of the same type, such as
integers, floating-point numbers, or characters.

Example: float grades[5] = {90.5, 85.0, 78.5, 92.0, 88.5};

4. Heterogeneous arrays: These are arrays that store elements of different data
types. Heterogeneous arrays are typically implemented using structures or classes
in programming languages that support them.

Example (in C using a structure):


```c
struct Data {
int integer;
float floating_point;
char character;
};

struct Data heterogeneous[3] = {


{1, 2.5, 'A'},
{2, 3.5, 'B'},
{3, 4.5, 'C'}
};
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

In summary, arrays are fundamental data structures used to store and organize
collections of elements. They can be classified based on their dimensions (1D or
multidimensional) and the type of elements they store (homogeneous or
heterogeneous). Arrays are characterized by their elements, indices, length or
size, and memory allocation.
B.solution.
Here's an algorithm to insert an element (2A) at position 2 in
the given array A = {10, 30, 40, 50}:

1. Initialize the given array A with elements {10, 30, 40, 50}.
2. Set the element to insert, element = 2 * A[1] (since position 2
has an index of 1).
3. Set the position to insert, position = 2.
4. Determine the length of the array, length = 4 (the number of
elements in the array A).
5. Create a new array B with a length equal to length + 1.
6. Set index = 0.
7. For each element in array A, do the following:
a. If index is less than the position, copy the element from
array A to array B at the same index.
b. If index is equal to the position, insert the element at this
index in array B.
c. If index is greater than the position, copy the element from
array A to array B at index + 1.
d. Increment the index.
8. Array B now contains the original elements with the new
element inserted at the specified position.

In this example, the algorithm will insert 2 * A[1] = 2 * 30 = 60


at position 2, resulting in the new array B = {10, 30, 60, 40, 50}.
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

15. What is stack ? Explain PUSH and POP operation


algorithm with example.
A stack is a linear data structure that follows the Last In First Out (LIFO) principle, meaning
that the most recently added element is the first one to be removed. It can be thought of as
a collection of items with two primary operations: push and pop. Stacks can be implemented
using arrays or linked lists.

1. Push operation: This operation adds an element to the top of the stack. If the stack has a
fixed size, the push operation first checks whether the stack is full. If the stack is full, it
returns an error or a message indicating that the stack is full. If the stack is not full, the new
element is added to the top of the stack, and the top pointer is updated.

Algorithm for the push operation:


```
function push(stack, element):
if stack is full:
return error or message "Stack is full"
else:
increment the top pointer
add the element to the top of the stack
```

Example: Let's say we have a stack with elements [10, 20, 30] and we want to push the
element 40 onto the stack. After performing the push operation, the stack will become [10,
20, 30, 40].

2. Pop operation: This operation removes the top element from the stack and returns its
value. If the stack has a fixed size, the pop operation first checks whether the stack is empty.
If the stack is empty, it returns an error or a message indicating that the stack is empty. If the
stack is not empty, the top element is removed from the stack, and the top pointer is
updated.

Algorithm for the pop operation:


```
function pop(stack):
if stack is empty:
return error or message "Stack is empty"
else:
store the top element in a temporary variable
decrement the top pointer
return the stored element
```
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

Example: Let's say we have a stack with elements [10, 20, 30, 40] and we want to perform
the pop operation. After performing the pop operation, the stack will become [10, 20, 30],
and the removed element (40) will be returned.

In summary, a stack is a LIFO data structure with two main operations: push and pop. The
push operation adds an element to the top of the stack, while the pop operation removes
the top element from the stack and returns its value. Stacks can be implemented using arrays
or linked lists and are commonly used for various applications, such as parsing expressions,
managing function calls, and implementing undo/redo functionality in software.

16.a Write an algorithm for bubble sort.


b. ) Sort the following elements using bubble sort.
38 47 24 42 1
a.solution.
Bubble sort is a simple comparison-based sorting algorithm that works by repeatedly
stepping through the list, comparing adjacent elements, and swapping them if they
are in the wrong order. The algorithm continues to do this until no more swaps are
needed, indicating that the list is sorted. Here's the algorithm for bubble sort:

1. Start at the beginning of the list.


2. Compare the first element with the second element.
a. If the first element is greater than the second element, swap them.
3. Move to the next element and compare it with the subsequent element.
a. If the current element is greater than the subsequent element, swap them.
4. Continue this process until the end of the list is reached.
5. After reaching the end of the list, if any swaps were made during the pass, repeat
steps 1-4. If no swaps were made, the list is sorted and the algorithm terminates.

Here's a more formalized version of the bubble sort algorithm:

```
function bubbleSort(list):
n = length of list
repeat
swapped = false
for i = 1 to n-1
if list[i-1] > list[i]
swap(list[i-1], list[i])
swapped = true
until not swapped
```
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

In this algorithm, the outer loop (repeat-until) iterates until no more swaps are
needed, and the inner loop (for) iterates through the list comparing and swapping
adjacent elements. The bubble sort algorithm has a worst-case time complexity of
O(n^2), where n is the number of elements in the list, but it can perform better
(O(n)) on already sorted or nearly sorted lists.

B.solution.
Here's a step-by-step process of sorting the given elements using bubble sort:

List: [38, 47, 24, 42, 1]

1. Pass 1:
- Compare 38 and 47, no swap needed.
- Compare 47 and 24, swap them: [38, 24, 47, 42, 1]
- Compare 47 and 42, swap them: [38, 24, 42, 47, 1]
- Compare 47 and 1, swap them: [38, 24, 42, 1, 47]

2. Pass 2:
- Compare 38 and 24, swap them: [24, 38, 42, 1, 47]
- Compare 38 and 42, no swap needed.
- Compare 42 and 1, swap them: [24, 38, 1, 42, 47]

3. Pass 3:
- Compare 24 and 38, no swap needed.
- Compare 38 and 1, swap them: [24, 1, 38, 42, 47]

4. Pass 4:
- Compare 24 and 1, swap them: [1, 24, 38, 42, 47]

After the 4th pass, no more swaps are needed, so the algorithm terminates. The
sorted list is: [1, 24, 38, 42, 47].

17.a. What is 'BST' ?


b.Construct a BST for the given below.

a.solution
BST stands for Binary Search Tree. It is a binary tree data structure in which each node has at
most two child nodes, arranged in such a way that:
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

1. The value of the node to the left is less than or equal to the value of the parent node.
2. The value of the node to the right is greater than or equal to the value of the parent node.

This property holds for each node in the Binary Search Tree, making it an ordered data
structure. BSTs are commonly used for searching, sorting, and managing ordered data. They
allow for efficient insertion, deletion, and lookup of elements, with average-case time
complexities of O(log n), where n is the number of nodes in the tree. However, in the worst
case (when the tree becomes completely unbalanced), the time complexity can degrade to
O(n).

Some common operations performed on Binary Search Trees include insertion, deletion,
searching for a specific value, finding the minimum and maximum values, and traversing the
tree in different orders (in-order, pre-order, and post-order traversals).

b.Solution
A Binary Search Tree (BST) is a binary tree data structure where each node has at most two child
nodes, arranged in a way such that the value of the node to the left is less than or equal to the value
of the parent node, and the value of the node to the right is greater than or equal to the value of the
parent node.

Here's a step-by-step construction of a BST for the given elements:

Elements: 56, 38, 10, 65, 72, 44, 50

1. Insert 56 as the root node.

```

56

```

2. Insert 38 (38 < 56, so it becomes the left child of 56).

```

56

/
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

38

```

3. Insert 10 (10 < 56 and 10 < 38, so it becomes the left child of 38).

```

56

38

10

```

4. Insert 65 (65 > 56, so it becomes the right child of 56).

```

56

/ \

38 65

10

```

5. Insert 72 (72 > 56 and 72 > 65, so it becomes the right child of 65).

```

56

/ \

38 65

/ \

10 72

```
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

6. Insert 44 (44 < 56 and 44 > 38, so it becomes the right child of 38).

```

56

/ \

38 65

/ \

10 72

44

```

7. Insert 50 (50 < 56, 50 > 38, and 50 > 44, so it becomes the right child of 44).

```

56

/ \

38 65

/ \

10 72

44

50

```

The final Binary Search Tree for the given elements is:

```

56

/ \

38 65
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

/ \

10 72

44

50

18.a. Define Hashing. Explain Hash table and Hash function.

b. Write 'C' program for Linear search.


a.solution.
Hashing is a technique that converts a given input (usually a large data item, such as a string
or a file) into a fixed-size output, called a hash value or hash code, using a mathematical
algorithm. Hashing is widely used in computer science for various applications, including
data storage, indexing, searching, and data integrity validation.

A Hash Table is a data structure that allows efficient storage and retrieval of data using the
concept of hashing. It stores data in an associative manner, using key-value pairs, where
each key is associated with a unique value. The hash table uses a hash function to calculate
an index for each key, which determines the position of the corresponding value in the table.
This allows for fast access to the desired data using the key.

A Hash Function is a mathematical function that takes an input (or a key) and returns a fixed-
size output, which is used as the index in the hash table. The primary goal of a hash function
is to distribute the keys uniformly across the hash table to minimize collisions (situations
where two or more keys have the same hash value). A good hash function should have the
following properties:

1. Deterministic: The same input (key) should always produce the same output (hash value).
2. Uniform distribution: The hash function should distribute the keys uniformly across the
hash table, minimizing the chances of collisions.
3. Fast computation: The hash function should be computationally efficient, allowing for fast
calculations of hash values.
4. Minimal collisions: Although it's impossible to avoid collisions entirely, a good hash
function should minimize the number of collisions.
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

In summary, hashing is a technique that converts input data into fixed-size output using a
mathematical algorithm. A hash table is a data structure that stores data in an associative
manner using key-value pairs and a hash function to calculate the index for each key. A hash
function is a mathematical function that generates a fixed-size output (hash value) from a
given input (key), with the aim of distributing the keys uniformly across the hash table,
minimizing collisions, and allowing for fast computation.

b.solution
Here's a simple C program to perform a linear search on an array of integers:

```c
#include <stdio.h>

int linearSearch(int arr[], int n, int target) {


for (int i = 0; i < n; i++) {
if (arr[i] == target) {
return i; // Target found, return its index
}
}
return -1; // Target not found, return -1
}

int main() {
int arr[] = {10, 20, 30, 40, 50, 60, 70, 80, 90};
int n = sizeof(arr) / sizeof(arr[0]);
int target;

printf("Enter the number to search: ");


scanf("%d", &target);
Assistant professor. 3rd Semester B.C.A Degree Examination, January-2024
Brijesh C G Data Structure (NEP Scheme)
2023 question paper and Solution

int result = linearSearch(arr, n, target);

if (result != -1) {
printf("Element found at index: %d\n", result);
} else {
printf("Element not found in the array.\n");
}

return 0;
}
```

In this program, the `linearSearch` function takes an array, the number of elements in the
array (n), and the target value to search for. It iterates through the array and compares each
element with the target. If the target is found, the function returns the index of the target
element. If the target is not found, the function returns -1.

The `main` function initializes an array of integers, reads the target value from the user, and
calls the `linearSearch` function. It then prints the result based on the returned index value.

You might also like