Data Structure-2021
Data Structure-2021
MADE BY:
MD. ASHIKUZZ ZAMAN (ASHIK)
ID: 220119
Question: (Part-A)
b. Write an Algorithm to Find the Difference Between the Summation of Boundary Elements and
the Summation of Diagonal Elements.
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.
c. What is a Circular Queue? Explain Its Operation with an Example and Mention Its Advantages
Over a Traditional Queue.
Answer:
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
Operations on Array:
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.
Function Definition:
f(n) = 1 if n = 1
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:
Control structures enable efficient programming by reducing redundancy and allowing dynamic
decision-making.
Algorithm:
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];
c. Recursion
Recursion is a programming technique where a function calls itself directly or indirectly to solve a
problem.
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.
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:
Applications:
Algorithm:
Evaluate Expression: 5 2 * 3 6 2 ^ / + 5 5 - * - 2
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:
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
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;
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:
● 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?
● Explain any one technique to find the minimum cost spanning tree with an example.
a. What is Hashing?
● Mention some techniques of hashing and explain one of them.
● 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?
8. Sorting Algorithms
Answer:
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:
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.
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?
● Min Heap: The key at each node is less than or equal to the keys of its children.
Min Heap
Delete 52:
Resulting Heap:
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)
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
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:
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 * +
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.
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.
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:
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.
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.
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.a) How does Quick Sort work? Explain with the given list of data: [5, 3, 7,
2, 9, 4, 8]
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.
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.
Formal Steps:
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.
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.
● 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