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

Data Structure-2021

Data structure

Uploaded by

ashik.cse.pust
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Data Structure-2021

Data structure

Uploaded by

ashik.cse.pust
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Data Structure

For 2.1 Exam-2023

MADE BY:
MD. ASHIKUZZ ZAMAN (ASHIK)

ID: 220119
Question: (Part-A)

1. Data Structures and Abstract Data Types


a. Define Data Structure with Example. State the Operations of Data Structure with Proper
Examples.

b. What is Abstract Data Type? Explain It.

c. Write a Recursive Function for the Mathematical Function:

● f(n)=1f(n) = 1f(n)=1 if n=1n = 1n=1


● f(n)=2×f(n−1)f(n) = 2 \times f(n-1)f(n)=2×f(n−1) if n≥2n \geq 2n≥2

2. Control Structures and Algorithms


a. Write Short Notes on Control Structure.

b. Write an Algorithm to Find the Difference Between the Summation of Boundary Elements and
the Summation of Diagonal Elements.

c. What Do You Mean by Recursion? Explain Its Mandatory Criterions.

3. Stacks, Postfix Expression, and Binary Trees


a. What is a Stack? Mention Some Applications of Stack. Explain Its Operations with an Example.

b. Write an Algorithm to Evaluate a Postfix Expression. Evaluate the Postfix Expression: 5 2 *


362^ / + 55 - * - 2

c. A Binary Tree T Has 9 Nodes. The Inorder and Preorder Traversals Yield the Following
Sequences of Nodes:

● Inorder: E ACKFHDBG
● Preorder: FAEKCDHGB
● Draw the Tree with Procedural Explanation.

4. Linked Lists and Circular Queues


a. What is a Linear Linked List? Explain with an Example and Summarize Its Advantages and
Disadvantages.

b. Write an Algorithm/Procedure to Perform the Following Operations on a Singly Linked List:

● (i) Insert New Node at the Beginning of the List.


● (ii) Count the Number of Nodes.

c. What is a Circular Queue? Explain Its Operation with an Example and Mention Its Advantages
Over a Traditional Queue.
Answer:

a. Data Structure Definition and Operations

A data structure is a way to organize and store data to enable efficient access and modification. It
is an essential concept in computer science for managing data.

Example: Array

An array is a collection of elements stored at contiguous memory locations. It allows indexed


access to elements.

Operations on Array:

1. Insertion: Adding an element at a specific index.


○ Example: Insert 10 at index 2 in an array [1, 2, 3, 4] resulting in [1, 2, 10,
3, 4].
2. Deletion: Removing an element from a specific index.
○ Example: Delete element at index 1 in [1, 2, 10, 3, 4] resulting in [1, 10,
3, 4].
3. Traversal: Accessing each element of the array.
○ Example: Print elements in [1, 10, 3, 4], resulting in 1, 10, 3, 4.
4. Search: Finding an element in the array.
○ Example: Search for element 10 in [1, 10, 3, 4], which is found at index 1.
5. Update: Changing the value of an element.
○ Example: Update element at index 2 in [1, 10, 3, 4] to 5, resulting in [1, 10,
5, 4].

b. Abstract Data Type (ADT)

An Abstract Data Type (ADT) is a theoretical concept that defines a data structure by its behavior
(operations) rather than its implementation. It specifies what operations are to be performed but
not how these operations will be implemented.
Example: Stack ADT

● Operations:
○ push(element): Add an element to the stack.
○ pop(): Remove and return the top element from the stack.
○ peek(): Return the top element without removing it.
○ isEmpty(): Check if the stack is empty.

a. Recursive Function for Mathematical Function

Function Definition:

f(n) = 1 if n = 1

f(n) = 2 * f(n-1) if n >= 2

Recursive Function in Python:

def f(n):

if n == 1:

return 1

else:

return 2 * f(n - 1)
2.a Control Structures

Control structures in programming dictate the flow of execution in a program based on certain
conditions or loops. They help manage the program's decision-making process and repetitive
tasks. The three main types of control structures are:

1. Sequential Control Structure:


○ Executes statements in a linear, step-by-step order.
○ Example: Regular code blocks where instructions are executed one after another.
2. Selection/Decision Control Structure:
○ Allows the program to make decisions and execute certain blocks of code based on
conditions.
○ Types:
■ if statement: Executes a block of code if a specified condition is true.
■ if-else statement: Executes one block of code if the condition is true, and
another block if the condition is false.
■ switch statement: Allows multi-way branching, executing different code
based on the value of an expression.
3. Repetition/Looping Control Structure:
○ Repeats a block of code multiple times until a condition is met or becomes false.
○ Types:
■ for loop: Repeats code a fixed number of times.
■ while loop: Repeats code while a condition remains true.
■ do-while loop: Executes the code at least once and then repeats while the
condition is true.

Control structures enable efficient programming by reducing redundancy and allowing dynamic
decision-making.

b. Algorithm for Boundary and Diagonal Element Sum

Algorithm:

1. Initialize boundary_sum and diagonal_sum to 0.


2. For each element matrix[i][j]:
○ If i == 0 or i == n-1 or j == 0 or j == n-1 (boundary condition), add to
boundary_sum.
○ If i == j (primary diagonal) or i + j == n-1 (secondary diagonal), add to
diagonal_sum.
3. Compute the difference: difference = boundary_sum - diagonal_sum.
4. Return or print difference.

int boundaryDiagonalDifference(int matrix[100][100], int n) {

int boundary_sum = 0, diagonal_sum = 0;

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

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

if (i == 0 || i == n - 1 || j == 0 || j == n - 1) {

boundary_sum += matrix[i][j];

if (i == j) {

diagonal_sum += matrix[i][j];

if (i + j == n - 1 && i != j) {

diagonal_sum += matrix[i][j];

return boundary_sum - diagonal_sum;

c. Recursion

Recursion is a programming technique where a function calls itself directly or indirectly to solve a
problem.

Mandatory Criteria for Recursion:

1. Base Case: Condition under which the recursion stops. This prevents infinite recursion.
2. Recursive Case: The part of the function that includes the recursive call.

Example Function for Factorial:

def factorial(n):

if n == 0:
return 1

else:

return n * factorial(n - 1)

3. Stack
a. Stack

A stack is a data structure that follows the Last In First Out (LIFO) principle. Elements can only be
added or removed from the top of the stack.

Operations:

1. Push: Add an element to the top of the stack.


○ Example: Push 10 onto [1, 2, 3], resulting in [1, 2, 3, 10].
2. Pop: Remove and return the top element from the stack.
○ Example: Pop from [1, 2, 3, 10], resulting in the stack [1, 2, 3] and the
popped element 10.
3. Peek: View the top element without removing it.
○ Example: Peek on [1, 2, 3, 10], resulting in 10.

Applications:

1. Function Call Management: Keeps track of function calls and returns.


2. Expression Evaluation: Used in parsing and evaluating expressions.
3. Backtracking Algorithms: Helps in scenarios like maze solving.

b. Postfix Expression Evaluation Algorithm

Algorithm:

1. Initialize an empty stack.


2. Read the postfix expression from left to right.
3. For each token:
○ If it's an operand, push it onto the stack.
○ If it's an operator, pop two elements from the stack, apply the operator, and push
the result back onto the stack.
4. After processing all tokens, the result will be on the top of the stack.

Evaluate Expression: 5 2 * 3 6 2 ^ / + 5 5 - * - 2

int evaluatePostfix(string expression) {


stack<int> s;
for (int i = 0; i < expression.length(); i++) {
char c = expression[i];
if (c == ' ') continue;
if (isdigit(c)) {
int num = 0;
while (isdigit(expression[i])) {
num = num * 10 + (expression[i] - '0');
i++;
}
i--;
s.push(num);
} else {
int val2 = s.top(); s.pop();
int val1 = s.top(); s.pop();
switch (c) {
case '+': s.push(val1 + val2); break;
case '-': s.push(val1 - val2); break;
case '*': s.push(val1 * val2); break;
case '/': s.push(val1 / val2); break;
case '^': s.push(pow(val1, val2)); break;
}
}
}
return s.top();
}

c. Binary Tree Traversal

Given:

● Inorder: E A C K F H D B G
● Preorder: F A E K C D H G B

In a Preorder sequence, the leftmost element is the root of the tree. So we know ‘F’
is the root for given sequences. By searching ‘F’ in the Inorder sequence, we can
find out all elements on the left side of ‘F’ is in the left subtree and elements on
right in the right subtree. So we know the below structure now.
4a. Linear Linked List

A linear linked list is a collection of nodes where each node contains data and a reference to the
next node in the sequence.

Example:

● Nodes: A -> B -> C -> D -> None

Advantages:

● Dynamic size.
● Efficient insertions/deletions.
● Memory Efficiency
● Easy Implementation of Abstract Data Types
● More Efficient Sorting

Disadvantages:

● No random access.
● Extra memory for storing pointers.
● More Complex Implementation

4b.Singly Linked List Operations

(i) Insert New Node at Beginning:

void insertHead(int value) {

Node* newNode = new Node(value);

newNode->next = head;

head = newNode;

}
(ii) Count Number of Nodes:

int size() {

Node* temp=Head;

int sz=0;

while(temp != nullptr){

temp=temp->next;

sz++;

return sz;

4c. Circular Queue

Definition:
A Circular Queue is a linear data structure that follows the FIFO (First In, First Out) principle but
uses a circular arrangement of elements. It connects the end of the queue back to the beginning
to make a circular structure, thereby utilizing the entire array space efficiently.

Operations:

1. Enqueue: Add an element to the rear of the queue. If the rear reaches the end of the array,
it wraps around to the beginning if there is space available.
2. Dequeue: Remove an element from the front of the queue. The front pointer moves to the
next position in the circular fashion.
3. Peek: View the front element of the queue without removing it.
4. isEmpty: Check if the queue is empty. This is typically done by checking if the front and
rear pointers are equal.
5. isFull: Check if the queue is full. This can be determined by checking if the next position of
the rear pointer (in circular fashion) is the front pointer.
Linear Queue:

Circular Queue:

Advantages Over Traditional Queue

1. Efficient Space Utilization:


○ In a traditional queue, when the rear reaches the end of the array, the space at the
front may remain unused even though it could potentially be utilized. A circular
queue overcomes this issue by reusing the empty space.
2. Avoids Wasting Space:
○ Circular queues make better use of the available space by wrapping around to the
beginning of the array. This reduces wasted memory and optimizes resource use.
3. Simplified Implementation:
○ The circular nature simplifies the implementation of operations such as enqueue
and dequeue by eliminating the need to shift elements.
4. Fixed Size:
○ Like traditional queues, circular queues also have a fixed size. However, their
circular nature helps in making the fixed size more efficient.
Question:(part-B)

5. Binary Trees and Heaps

a. How a Binary Tree Can Be Stored in Computer Memory Using an Array

b. What is a Binary Search Tree?

● Construct a Binary Search Tree with the following values: 50, 15, 10, 13, 20, 22, 55, 60, 42,
57.
● Traverse the tree in preorder and postorder.

c. What is a Heap?

● Explain the creation process of a Min Heap with the following data: 45, 28, 52, 25, 60, 70.
● If you delete the node 52, what will be the result?

6. Graphs and Trees

a. Consider the Following Graph

Produce the output of BFS and DFS starting from node A.

b. What is a Spanning Tree?

● Explain any one technique to find the minimum cost spanning tree with an example.

c. Construct an Expression Tree

● For the expression: (a + bc) + ((de + 1) * g).


● Provide the outputs for preorder, inorder, and postorder traversals.

7. Hashing and Collisions

a. What is Hashing?
● Mention some techniques of hashing and explain one of them.

b. What is Hash Collision?

● Suppose a hash table contains 11 memory locations and a file contains 8 records Where:

● Using the linear probing method, show how the records will appear in memory.

c. What is Sorting?

● Classify sorting methods.


● Explain Selection Sort with the following data: [5, 3, 7, 2, 9, 4, 8].

8. Sorting Algorithms

a. How Quick Sort Works

● Explain Quick Sort with the following data: [5, 3, 7, 2, 9, 4, 8].

b. Formal Algorithm for Merge Sort

c. Explain the Shortest Path Algorithm with an Example

Answer:

5a.How a Binary Tree Can Be Stored in Computer Memory Using an Array

A binary tree can be stored in computer memory using an array in a way that allows for efficient
access and manipulation. This approach is especially useful for complete or nearly complete
binary trees. Here’s how you can do it:

1. Structure of the Array

In this method, the binary tree is represented as a complete binary tree, where each level of the
tree is fully filled except possibly the last level. The array index represents the position of each
node in the tree.

● Root Node: The root of the binary tree is stored at index 0.


● Left Child: For a node at index i, its left child is stored at index 2i + 1.
● Right Child: For a node at index i, its right child is stored at index 2i + 2.
● Parent Node: For a node at index i, its parent is stored at index (i - 1) / 2 (using
integer division).

5b. b. What is a Binary Search Tree? Construct a Binary Search Tree with the
Following Values: 50, 15, 10, 13, 20, 22, 55, 60, 42, 57. Traverse the Tree in Preorder
and Postorder.

Binary Search Tree (BST): A binary search tree follows some order to arrange the
elements. In a Binary search tree, the value of left node must be smaller than the
parent node, and the value of right node must be greater than the parent node. This
rule is applied recursively to the left and right subtrees of the root.

Preorder Traversal (Root, Left, Right): 50, 15, 10, 13, 20, 22, 42, 55, 60, 57

Postorder Traversal (Left, Right, Root): 13, 10, 22, 42, 20, 15, 57, 60, 55, 50

c. What is a Heap? Explain the Creation Process of a Min Heap with the Following
Data: 45, 28, 52, 25, 60, 70. If You Delete the Node 52, What Will Be the Result?

Heap: A heap is a binary tree where:

● Min Heap: The key at each node is less than or equal to the keys of its children.

Creation of Min Heap:

1. Insert 45: Root.


2. Insert 28: 28 is less than 45, so it becomes the root and 45 becomes its child.
3. Insert 52: 52 is greater than 28, so it becomes the right child of 45.
4. Insert 25: 25 is less than 28, so it becomes the root, and 28 is adjusted as the child.
5. Insert 60: 60 is greater than 28 and 45, so it is added as the right child of 45.
6. Insert 70: 70 is greater than 60, so it becomes the right child of 60.

Min Heap

Delete 52:

1. Replace 52 with the last element (70).


2. Heapify to restore min heap property.

Resulting Heap:

6.a. BFS and DFS of the graph

Given the graph, the nodes are A, B, C, D, and E. We need to determine the output for
Breadth-First Search (BFS) and Depth-First Search (DFS) starting from node A.
BFS (Breadth-First Search)

In BFS, we explore each node level by level. Starting from A:

1. Start with A.
2. Visit all neighbors of A: B and E.
3. Visit neighbors of B: C and D.
4. Visit the remaining neighbor of E.

Output: A, B, E, C, D

DFS (Depth-First Search)

In DFS, we explore each node as far as possible before backtracking. Starting from A:

1. Start with A.
2. Move to a neighbor of A, say B.
3. From B, visit a neighbor, say C.
4. From C, backtrack to B and explore D.
5. Backtrack to A, explore E.

Output: A, B, C, D, E

b. Spanning Tree

A spanning tree of a graph is a subgraph that connects all the vertices together
without any cycles and with the minimum number of edges (|V| - 1, where |V| is the
number of vertices).

Minimum Cost Spanning Tree (MST): It is a spanning tree in which the total weight of
the edges is minimized. One common technique to find an MST is Kruskal's algorithm:

1. Sort all the edges in increasing order of their weight.


2. Pick the smallest edge. If it doesn’t form a cycle, include it in the MST.
3. Repeat until the tree contains (V - 1) edges.

Example: Consider a graph with edges:

● A-B with weight 1


● B-C with weight 2
● A-C with weight 3

The MST would include edges A-B and B-C, avoiding the higher weight edge A-C.

c. Expression Tree
The expression is:
(a + b * c) + ((d * e + 1) * g)
1. Constructing the Expression Tree:

2. Traversals:
○ Preorder (Root, Left, Right):
+ + a * b c * + * d e 1 g
○ Inorder (Left, Root, Right):
a + b * c + d * e + 1 * g
○ Postorder (Left, Right, Root):
a b c * + d e * 1 + g * +

7.a) What is Hashing? Mention some techniques of hashing and explain


one of them.

Hashing is a process that transforms data (like a key) into a fixed-size value or hash
code. This value is used to quickly locate the data in a hash table. It helps in fast
retrieval, insertion, and deletion of data. The hash function is used to calculate the hash
code for the given data, which determines the index where the data will be stored.

Hashing Techniques:

1. Direct hashing
2. Modular hashing
3. Folding method
4. Multiplication method
Example: Modular Hashing – In this method, the key is divided by the size of the hash
table (usually a prime number), and the remainder is taken as the index in the table.
For example, if the hash table size is 10 and the key is 56, the hash value would be 56
mod 10 = 6.

Let's go through the questions:

a) What is Hashing? Mention some techniques of hashing and explain


one of them.

Hashing is a process that transforms data (like a key) into a fixed-size value or hash
code. This value is used to quickly locate the data in a hash table. It helps in fast
retrieval, insertion, and deletion of data. The hash function is used to calculate the hash
code for the given data, which determines the index where the data will be stored.

Hashing Techniques:

1. Direct hashing
2. Modular hashing
3. Folding method
4. Multiplication method

Example: Modular Hashing – In this method, the key is divided by the size of the hash
table (usually a prime number), and the remainder is taken as the index in the table.
For example, if the hash table size is 10 and the key is 56, the hash value would be 56
mod 10 = 6.

b) What is hash collision? (Linear Probing)

A hash collision occurs when two different keys produce the same hash address or
index in the hash table. This can happen when a hash function maps multiple keys to
the same location.
To handle collisions, several methods can be used. One common method is linear
probing, which means that when a collision occurs, you check the next available
memory slot (i.e., increase the index by 1 until an empty spot is found).

Given:

● The table has 11 memory locations.


● Using linear probing, the records will be placed as follows:

Now, based on linear probing:

● Record A goes to slot 4.


● Record B goes to slot 8.
● Record C goes to slot 2.
● Record D goes to slot 11.
● Record E also hashes to 4, but since slot 4 is taken by A, using linear probing, it
goes to slot 5.
● Record F hashes to 11, but since slot 11 is occupied by D, it goes to the next free
slot, which is slot 0 (wrapping around the table).
● Record G hashes to slot 5, but since it's already occupied by E, it goes to slot 6.
● Record H goes to slot 1.

Thus, the final memory positions after linear probing will be:

● Slot 0: F
● Slot 1: H
● Slot 2: C
● Slot 4: A
● Slot 5: E
● Slot 6: G
● Slot 8: B
● Slot 11: D
c) What is sorting? Explain Selection Sort.

Sorting is the process of arranging data in a particular order (ascending or descending).


There are many sorting algorithms, such as:

1. Bubble sort
2. Selection sort
3. Insertion sort
4. Merge sort
5. Quick sort

Selection Sort:

● This algorithm sorts by repeatedly selecting the smallest (or largest) element
from the unsorted portion of the list and swapping it with the element at the
current position.

Steps for Selection Sort (for list [5, 3, 7, 2, 9, 4, 8]):

1. First, find the smallest element in the list (2) and swap it with the first element (5).
○ Result: [2, 3, 7, 5, 9, 4, 8]
2. Then, find the smallest element in the remaining unsorted part [3, 7, 5, 9, 4, 8]
(which is 3) and leave it in place.
○ Result: [2, 3, 7, 5, 9, 4, 8]
3. Now, find the smallest element in the remaining part [7, 5, 9, 4, 8] (which is 4) and
swap it with 7.
○ Result: [2, 3, 4, 5, 9, 7, 8]
4. Continue this process until the list is fully sorted.
○ Final sorted list: [2, 3, 4, 5, 7, 8, 9]

These are the solutions to the questions in the image. Let me know if you need further
clarification!

8 – May be out of syllebus

8.a) How does Quick Sort work? Explain with the given list of data: [5, 3, 7,
2, 9, 4, 8]

Quick Sort is a divide-and-conquer algorithm. It works by selecting a 'pivot' element


from the array and partitioning the other elements into two sub-arrays, according to
whether they are less than or greater than the pivot. The sub-arrays are then sorted
recursively.

Steps for Quick Sort:

1. Choose a Pivot: Select the pivot element (typically the last element in the list,
though other choices are also possible).
2. Partitioning: Reorder the array so that elements less than the pivot come before
it, and elements greater than the pivot come after it. After partitioning, the pivot
is in its correct position.
3. Recursively Apply: Recursively apply the above steps to the sub-arrays of
elements with smaller and larger values.

Example with the given list [5, 3, 7, 2, 9, 4, 8]:

1. Select pivot: 8 (last element).


2. Partition: [5, 3, 7, 2, 4] (all less than 8) and [9] (greater than 8). Now, the list looks
like [5, 3, 7, 2, 4, 8, 9].
3. Recursively apply quick sort to the left sub-array [5, 3, 7, 2, 4]:
○ Select pivot: 4
○ Partition: [3, 2] (less than 4) and [5, 7] (greater than 4). Now, the list looks
like [3, 2, 4, 5, 7, 8, 9].
4. Continue recursively:
○ On [3, 2]: Select pivot: 2
○ Partition: [2, 3]
○ Result after sorting: [2, 3, 4, 5, 7, 8, 9]

Thus, the sorted list is [2, 3, 4, 5, 7, 8, 9].

EXTRA:
b) Write down the formal algorithm for Merge Sort

Merge Sort is also a divide-and-conquer algorithm. It divides the array into two halves,
recursively sorts them, and then merges the two sorted halves.

Algorithm for Merge Sort:

1. Divide the array into two halves.


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

Formal Steps:

1. If the array has one or zero elements, return it (base case).


2. Split the array into two halves.
3. Recursively sort both halves.
4. Merge the sorted halves using the following procedure:
○ Compare the elements of both halves and copy the smaller element into
the result array.
○ Continue until all elements are merged.

Pseudocode Algorithm:
c) Explain the Shortest Path Algorithm with an example

The shortest path algorithms are the ones that focuses on calculating the minimum
travelling cost from source node to destination node of a graph in optimal time and
space complexities.

Breadth-First Search (BFS) for Shortest Path:

BFS is an excellent algorithm for finding the shortest path in unweighted graphs. The reason it
works is that it explores nodes level by level, starting from the source node. It first visits all nodes
that are directly connected to the source (distance = 1), then all nodes that are two steps away
(distance = 2), and so on.

Why does it work?

● BFS processes nodes in "layers" or "levels" of distance from the starting node.
● This ensures that when BFS first visits a node, it has found the shortest path to that node.

Algorithm :

1. Initialize a Queue: Use a queue to store pairs of {node, distance}. Start by pushing the
source node with a distance of 0, i.e., {src, 0}.
2. Mark Source as Visited: Track visited nodes to avoid reprocessing the same node.
3. Process Each Node in the Queue:
○ While the queue is not empty:
■ Get the node and its current distance from the front of the queue.
■ Mark the node as "visited" and record its distance.
■ For each unvisited neighbor of this node:
■ Push {neighbor, distance + 1} to the queue.
■ Mark the neighbor as visited.
4. Repeat Until All Nodes are Processed.
The End
Data structure question - 2021

You might also like