Prabhjot Dsa Assignment
Prabhjot Dsa Assignment
ANSWER 1:
A data structure is a specific way of organizing and storing data in a computer so it
can be accessed and modified efficiently. It provides a means to manage and process data,facilitating
operations like data retrieval, insertion, deletion, and manipulation.
Linear Data Structures: These store elements sequentially and are easy to traverse since elements are
arranged in a specific order. They are generally simple to implement but mayhave limitations in terms of
efficiency when scaling.
1. Array: A collection of elements, identified by index or key, stored sequentially in memory. All elements are
of the same data type. Arrays allow constant-time access to elements but havefixed size and may require
significant memory if large.
2. Linked List: A collection of nodes where each node contains a data part and a reference (orlink) to the
next node in the sequence. Linked lists allow for efficient insertions and deletions but have a slower access
time than arrays due to the need to traverse nodes.
Singly Linked List: Each node points to the next node.
Doubly Linked List: Each node points to both the next and the previous node.
Circular Linked List: The last node points back to the first, forming a loop.
Stack: A collection of elements that follows the Last In, First Out (LIFO) principle. Operationsare
performed at one end, called the "top" of the stack. Common operations include push (insert) and pop
(remove). Stacks are used for functions like backtracking, reversing, and recursion management.
Queue: A collection of elements that follows the First In, First Out (FIFO) principle. Elementsare added at
the back (enqueue) and removed from the front (dequeue). Queues are used in scheduling processes and
managing tasks in order.
1. Simple Queue: Basic FIFO structure.
2. Circular Queue: The end of the queue wraps around to connect with the start,optimizing
space.
3. Priority Queue: Elements are dequeued based on priority rather than order ofarrival.
4. Dequeue: A double-ended queue where insertions and deletions can be made fromboth ends.
A data structure is a specific way of organizing and storing data in a computer so it can be accessed and
modified efficiently. It provides a means to manage and process data, facilitatingoperations like data retrieval,
insertion, deletion, and manipulation.
1. Linear Data Structures: These store elements sequentially and are easy to traverse sinceelements are
arranged in a specific order. They are generally simple to implement but may have limitations in terms
of efficiency when scaling.
2. Non-Linear Data Structures: These store elements in a hierarchical or interconnected manner,
allowing for more complex relationships among data. Non-linear structures areefficient for certain
tasks, such as representing hierarchical data or graphs, but can be more complex to implement.
Linear Data Structures
1. Array: A collection of elements, identified by index or key, stored sequentially in memory. All
elements are of the same data type. Arrays allow constant-time access toelements but have fixed
size and may require significant memory if large.
2. Linked List: A collection of nodes where each node contains a data part and a reference(or link) to the
next node in the sequence. Linked lists allow for efficient insertions and deletions but have a slower
access time than arrays due to the need to traverse nodes.
o Singly Linked List: Each node points to the next node.
o Doubly Linked List: Each node points to both the next and the previous node.
o Circular Linked List: The last node points back to the first, forming a loop.
3. Stack: A collection of elements that follows the Last In, First Out (LIFO) principle. Operations are
performed at one end, called the "top" of the stack. Common operations include push(insert) and pop
(remove). Stacks are used for functions like backtracking,reversing, and recursion management.
4. Queue: A collection of elements that follows the First In, First Out (FIFO) principle. Elements are
added at the back (enqueue) and removed from the front (dequeue). Queuesare used in scheduling
processes and managing tasks in order.
o Simple Queue: Basic FIFO structure.
o Circular Queue: The end of the queue wraps around to connect with the start,optimizing
space.
o Priority Queue: Elements are dequeued based on priority rather than order ofarrival.
o Deque: A double-ended queue where insertions and deletions can be made fromboth ends.
1. Tree: A hierarchical structure consisting of nodes. Each node contains a data value andlinks to child
nodes. The topmost node is the "root," and nodes with no children are "leaves." Trees are efficient for
hierarchical data storage, such as file systems and databases.
o Binary Tree: Each node has at most two children (left and right).
o Binary Search Tree (BST): A binary tree with sorted nodes; left child values aresmaller, and
right child values are larger.
o AVL Tree: A self-balancing binary search tree that maintains balance throughrotations to
ensure efficient search and update operations.
o B-Tree: A balanced tree structure optimized for systems that read and write largeblocks of
data.
2. Graph: A structure consisting of nodes (vertices) connected by edges. Graphs representcomplex
relationships among data points and can be directed or undirected.
o Undirected Graph: Edges have no direction (mutual connection).
o Directed Graph (Digraph): Edges have direction (one-way connection).
o Weighted Graph: Edges have weights (values) representing cost, distance, orother
factors.
o Unweighted Graph: Edges have no weight.
3. Heap: A specialized tree-based structure that follows the heap property. It is commonlyused to
implement priority queues.
o Max-Heap: The value of each parent node is greater than or equal to the values ofits children.
o Min-Heap: The value of each parent node is less than or equal to the values of itschildren.
ANSWER 2:
An Abstract Data Type (ADT) is a theoretical model for data structures that definesa set of data
and the operations that can be performed on it without specifying the actual implementation details. An ADT
focuses on what operations can be done (the interface) ratherthan how they are done (the implementation). This
abstraction allows programmers to use data structures in a more general way, focusing on functionality without
worrying about underlying complexities.
CHARACTERISTICS:
o Elements are arranged in a sequential order.
o Each element has a single predecessor and successor, except the first and last.
ANSWER 3:
Linear data structures support a variety of basic operations that are essential for manipulating and managing data.
Here are the primary operations commonly performed withlinear structures like arrays, linked lists, stacks, and
queues:
1. Traversal
Traversal is the process of accessing each element in the linear structure sequentially.
This operation is essential for displaying, processing, or analyzing each element.
For example, in an array or linked list, traversal involves moving from the first to the lastelement to
process each item.
2. Insertion
Insertion adds a new element at a specified position within the structure.
The specifics of insertion vary depending on the structure:
o Array: Adding an element in an array requires shifting existing elements, makinginsertion at
the start or middle costly (O(n) time complexity).
o Linked List: Inserting at the beginning or end is efficient (O(1) for singly linkedlists), as it
only requires updating pointers.
o Stack: Elements are pushed (inserted) only at the top of the stack.
o Queue: Elements are enqueued (inserted) at the back of the queue.
3. Deletion
Deletion removes an element from a specific position in the structure.
Similar to insertion, the specifics depend on the data structure:
o Array: Removing an element in an array may require shifting elements tomaintain
order, which can be costly.
o Linked List: Deleting the first node or a specific node is straightforward byupdating
pointers.
o Stack: Elements are popped (removed) only from the top.
o Queue: Elements are dequeued (removed) from the front.
4. Searching
Searching involves finding the location of a particular element within the structure.
Searching methods vary based on the data structure:
o Array and Linked List: A linear search (O(n)) is used to locate an element bychecking
each item.
o Stack and Queue: Typically, only the element at the top (stack) or front (queue) isaccessible, so
searching isn’t commonly used for these structures.
5. Updating
Updating changes the value of an element at a specific position in the structure.
This operation is straightforward if the element's position is known (O(1) for direct-access
structures like arrays).
In a linked list, traversal may be necessary to reach the node before updating.
6. Accessing
Accessing retrieves the value of an element at a particular index or position in thestructure.
Array: Direct access is possible with indexing (O(1) time complexity).
Linked List: Accessing a specific node requires traversal from the start to the desiredposition,
making it an O(n) operation.
ANSWER 4:
In C, dynamic memory allocation allows for allocating and managing memory at
runtime, providing flexibility to create data structures that can grow or shrink as needed. The Cstandard library
provides four main functions for dynamic memory allocation, each defined in the <stdlib.h>header file:
EXAMPLE:
2. CALLOC(Contiguous Allocation)
Syntax: void* calloc(size_t num, size_t size);
Description: Allocates memory for an array of numelements, each of a specified size,and initializes all
bytes to zero.
Parameters: numis the number of elements, and sizeis the size in bytes of eachelement.
Return Value: Returns a void*pointer to the allocated and zero-initialized memory.Returns NULLif
the allocation fails.
EXAMPLE :
int* ptr = (int*)calloc(10, sizeof(int)); // Allocates and initializes memory for an array of 10integers to 0.
3. REALLOC (Reallocation)
Syntax: void* realloc(void* ptr, size_t new_size);
Description: Resizes a previously allocated memory block to a new size. It can increaseor decrease
the size of the memory block, copying the existing data to the new block. If ptris NULL, realloc
behaves like malloc.
Parameters:
o ptris a pointer to the previously allocated memory block (using malloc,calloc, or
realloc).
o new_sizespecifies the new size for the memory block in bytes.
Return Value: Returns a void*pointer to the reallocated memory. If reallocation fails,it returns NULL,
and the original memory block remains unchanged.
EXAMPLE:
4. FREE (Deallocation)
Syntax: void free(void* ptr);
Description: Frees the memory block previously allocated by malloc, calloc, or realloc. It releases
the memory back to the system, preventing memory leaks. Aftercalling free, the pointer becomes
invalid and should not be used until reallocated.
Parameters: ptris the pointer to the memory block to free.
#include <stdio.h>
#include <stdlib.h>int
main() {
// Allocate memory for an array of 5 integers using mallocint* arr =
(int*)malloc(5 * sizeof(int));
for(int i = 0; i < 5; i++) {
arr[i] = i + 1; printf("%d ",
arr[i]);
}
// Resize the array to hold 10 integers using reallocarr =
(int*)realloc(arr, 10 * sizeof(int));
ANSWER 5:
Linear Data Structures organize data in a sequential, ordered manner, where elements arearranged one after
another. This sequential setup means each element typically has a unique predecessor and successor, except for the
first and last elements in the structure. Common examples of linear data structures include arrays, linked lists,
stacks, and queues.
These structures are generally straightforward to implement and use, making them suitable for simpler tasks like
managing lists of items or processing tasks in a sequence. For instance, stacksand queues manage data in an
orderly way, following Last In, First Out (LIFO) and First In, First Out (FIFO) principles, respectively. Linear
data structures often allow direct access to elements, such as accessing elements by index in arrays. However,
they may require shifting elements for insertions and deletions, which can impact performance, especially for
large datasets.
Non-linear structures are ideal for modeling complex data like hierarchical relationships (such as file
directories) or interconnected data (like social networks). They tend to be more complexto implement due to
the varied relationships among elements, and traversal methods can be intricate, requiring specific techniques
(e.g., preorder, inorder, and postorder for trees).
ANSWER 6:
The time complexity and space complexity of an algorithm are metrics used to evaluate itsefficiency and
resource usage. They help in understanding the algorithm's performance, especially as the input size grows.
Time Complexity
Definition: Time complexity is a measure of the amount of time an algorithm takes torun as a
function of the input size, typically denoted as nnn.
Purpose: It gives an idea of how the execution time increases with the input size,helping to
predict the algorithm’s behavior on large datasets.
Notations: Big O notation (e.g., O(n)O(n)O(n), O(n2)O(n^2)O(n2), O(logn)O(\log n)O(logn)) is
used to express the upper bounds of time complexity, representing theworst-case scenario of time
growth.
Example: A linear search algorithm has a time complexity of O(n)O(n)O(n) because itmay need to
check each element in a list of nnn elements in the worst case.
Space Complexity
ANSWER 7:
Best case, average case, and worst case time analyses are used to describe an algorithm's performance
under different conditions of input data. Each provides insights into how efficiently an algorithm will run
depending on the scenario. Let’s go through each case withexamples:
1. Best Case
Definition: The best case time complexity of an algorithm is the minimum time it takesto complete,
given the most favorable input.
Purpose: This scenario is typically used to understand the fastest performance that analgorithm can
achieve.
Example: Consider linear search in an unsorted array.
o Best Case: The element to be found is the very first element in the array.
o Time Complexity: O(1)O(1)O(1), as the algorithm only needs one comparison tofind the
target element.
2. Average Case
Definition: The average case time complexity represents the expected time it takes foran algorithm to
complete, assuming random input distribution.
Purpose: This case gives a realistic measure of performance across a range of inputs,assuming no
particular bias.
Example: Again, consider linear search in an unsorted array.
o Average Case: The element is expected to be somewhere in the middle of thearray on
average.
o Time Complexity: O(n/2)O(n/2)O(n/2), which simplifies to O(n)O(n)O(n), as itmight take
approximately half of the array's length to find the element.
3. Worst Case
Definition: The worst case time complexity is the maximum time an algorithm takes tocomplete,
given the most challenging input.
Purpose: This case helps to identify performance limits and ensure the algorithm won’texceed certain
time constraints, even in the most difficult scenarios.
Example: Consider linear search again.
o Worst Case: The element is located at the last position or is not in the array at all.
o Time Complexity: O(n)O(n)O(n), as the algorithm must examine each element inthe array to
confirm the element's absence or to find it at the end.
Best Case: If the array is already sorted, Bubble Sort will only make one pass withoutneeding to
swap elements.
o Time Complexity: O(n)O(n)O(n).
Average Case: When the elements are in random order, Bubble Sort has to go throughmultiple passes
and perform several swaps.
o Time Complexity: O(n2)O(n^2)O(n2).
Worst Case: If the array is in reverse order, Bubble Sort must swap every pair on eachpass, making
it go through the maximum number of comparisons and swaps.
o Time Complexity: O(n2)O(n^2)O(n2).
ANSWER 8:
Performance analysis is the process of evaluating an algorithm to determine its efficiency and effectiveness in
solving a specific problem. This analysis involves studying various factors suchas time complexity, space
complexity, and resource utilization under different conditions of input data. The goal is to understand how well
the algorithm performs, especially as the size of the input data grows.
1. Time Complexity: This measures the amount of time an algorithm takes to complete as afunction of the
input size. Different cases (best, average, worst) are often analyzed to provide a comprehensive view of
expected performance.
2. Space Complexity: This assesses the amount of memory space required by the algorithm in relation to
the input size. Like time complexity, it can also be evaluated under differentconditions.
3. Scalability: Analyzing how the algorithm's performance changes with increasing inputsizes is crucial
for determining its applicability in real-world scenarios.
4. Resource Usage: Besides time and space, performance analysis can include evaluatingthe
algorithm's use of other resources, such as CPU cycles and network bandwidth, depending on the
context.
#include <iostream>
#include <vector>
#include <chrono> using
namespace std;
using namespace std::chrono;
return sum;
int main() {
// Example vector
cout << "Sum of vector values: " << result << endl;
cout << "Execution time: " << duration.count() << " microseconds" << endl;
return 0;
}
Answer:
Sparse Matrix:
A sparse matrix is a matrix in which most of the elements are zero (or a predefined "empty" value). This is
in contrast to a dense matrix, where most of the elements are non-zero. Sparse matrices arise frequently in
scientific computing, image processing, and other areas where the data is large but sparse.
Using Array:
In an array-based representation of a sparse matrix, only the non-zero elements are stored along with their
row and column indices. This reduces memory usage significantly. There are a few common ways to store
sparse matrices:
Triplet Format (COO - Coordinate List): The sparse matrix is stored as a list of non-zero values,
along with their row and column indices.
A = [0, 0, 0, 0]
[5, 0, 0, 0]
[0, 8, 0, 0]
[0, 0, 0, 4]
In this format, the matrix is represented as an array of tuples or a 3-column array (row, column, value).
Compressed Sparse Row (CSR) and Compressed Sparse Column (CSC) are other formats that
store row/column indices separately, further reducing memory.
In the linked list representation of a sparse matrix, each non-zero element is stored in a node that contains:
The row index.
The column index.
The value of the non-zero element.
A pointer to the next element in the list.
A linked list can be implemented in a row-wise or column-wise manner. It helps in saving memory,
especially when the number of non-zero elements is significantly less than the total number of elements.
Ques 2: Find the Address of Element A1(4, 12) in a Two-Dimensional Array Stored in Row-Major
Order
Answer:
Given:
For a two-dimensional array A[i][j]A[i][j]A[i][j] with base address BBB, the address of element A[i,j]A[i,
j]A[i,j] is given by:
Here:
Number of rows = 8 - 1 + 1 = 8
Number of columns = 14 - 7 + 1 = 8
i=4,j=12i = 4, j = 12i=4,j=12
Address(4,12)=100+4×((4−1)×8+(12−7))=100+4×(24+5)=100+4×29=100+116=216
Ques 3: Find the Address of Element Z1(4, 12) in a Two-Dimensional Array Stored in Column-Major
Order
Answer:
Given:
For a two-dimensional array Z[i][j]Z[i][j]Z[i][j] with base address BBB, the address of element Z[i,j]Z[i,
j]Z[i,j] is given by:
Here:
Number of rows = 9 - 2 + 1 = 8
Number of columns = 18 - 9 + 1 = 10
i=4,j=12i = 4, j = 12i=4,j=12
Address(4,12)=100+4×((12−1)×8+(4−1))=100+4×(11×8+3)=100+4×(88+3)=100+4×91=100+364=464
Stack
Ques 1: What is a Stack? Explain Basic Primitive Operations of Stack with Examples
Answer:
A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. This means that the
last element inserted into the stack is the first to be removed.
Example:
Ques 2: Write a C Program to Implement a Stack with Overflow and Underflow Checks Using Array
Answer:
#include <stdio.h>
#define MAX 5
int stack[MAX];
int top = -1;
int isFull() {
return top == MAX - 1;
}
int isEmpty() {
return top == -1;
}
int pop() {
if (isEmpty()) {
printf("Stack Underflow\n");
return -1;
} else {
return stack[top--];
}
}
int peek() {
if (isEmpty()) {
printf("Stack is empty\n");
return -1;
} else {
return stack[top];
}
}
int main() {
push(10);
push(20);
push(30);
printf("Top element is %d\n", peek());
printf("%d popped from stack\n", pop());
printf("Top element is %d\n", peek());
return 0;
}
Answer:
Algorithm:
Algorithm Steps:
Ques 4: What is the Advantage of Polish Expression Over Infix Notation? Write an Algorithm to
Convert Infix to Reverse Polish Notation (Postfix)
Answer:
No Parentheses Needed: Polish notation (both prefix and postfix) eliminates the need for
parentheses to enforce operator precedence.
Faster Evaluation: It allows for faster computation because the order of operations is explicitly
defined.
1. Initialize an empty stack for operators and an empty list for the result.
2. For each character in the infix expression:
o If it's an operand, add it to the result list.
o If it's an operator, pop operators from the stack to the result list until the operator at the top of
the stack has lower precedence, then push the current operator onto the stack.
o If it's a parenthesis, handle it by pushing it onto the stack or popping operators until a left
parenthesis is encountered.
3. Pop any remaining operators from the stack to the result list.
Answer:
To convert an infix expression to postfix, we use a stack-based algorithm that respects operator precedence
and parentheses.
Operator Precedence:
1. Initialize an empty stack for operators and an empty list for the result.
2. For each token (operand or operator) in the infix expression:
o If the token is an operand (variable or number), append it to the result list.
o If the token is an operator, pop operators from the stack to the result list while they have
greater or equal precedence than the current operator. Then, push the current operator onto
the stack.
o If the token is a left parenthesis (, push it onto the stack.
o If the token is a right parenthesis ), pop operators from the stack to the result list until a left
parenthesis ( is encountered.
3. After reading the entire expression, pop any remaining operators from the stack to the result list.
1. Infix Expression: A + ( (B – C) * (D – E) + F) / G ) $ (H – J)
Postfix Expression: A B C – D E – * F + G / H J – $ +
Steps:
2. Infix Expression: (A + B) * (C – D) $ E * F
Postfix Expression: A B + C D – * E F * $
Steps:
1. Encounter ( → Push to stack
2. Encounter A → Append to result: A
3. Encounter + → Push + to stack
4. Encounter B → Append to result: A B
5. Pop + from stack → Append to result: A B +
6. Pop ( from stack → Discard
7. Encounter * → Push * to stack
8. Encounter ( → Push to stack
9. Encounter C → Append to result: A B + C
10. Encounter – → Push – to stack
11. Encounter D → Append to result: A B + C D
12. Pop – from stack → Append to result: A B + C D –
13. Pop * from stack → Append to result: A B + C D – *
14. Encounter $ → Push $ to stack
15. Encounter E → Append to result: A B + C D – * E
16. Encounter * → Push * to stack
17. Encounter F → Append to result: A B + C D – * E F
18. Pop * from stack → Append to result: A B + C D – * E F *
19. Pop $ from stack → Append to result: A B + C D – * E F * $
3. Infix Expression: (A + B) * (C ^ (D – E) + F) – G
Postfix Expression: A B + C D E – ^ F + * G –
Steps:
4. Infix Expression: A + B * C
Postfix Expression: A B C * +
Steps:
5. Infix Expression: A + B * C ^ D – E
Postfix Expression: A B C D ^ * + E –
Steps:
Postfix Expression: A B C + + D E F * + G / +
Steps:
7. Infix Expression: (A + B) * C / D + E ^ F / G
Postfix Expression: A B + C * D / E F ^ G / +
Steps:
8. Infix Expression: (A + B) * C / D
Postfix Expression: A B + C * D /
Steps:
Postfix Expression: A B + C D / – E /
Steps:
Postfix Expression: A B C D E ^ / – / F +
Steps:
Postfix Expression: A B C D E ^ * / –
Steps:
Let's evaluate the two postfix expressions, step by step, assuming that:
A=1
B=2
C=3
1. Postfix Expression: A B + C – B A + C - +
Final Result: 0
2. Postfix Expression: A B C + * C B A - + *
Push A (1): [1]
Push B (2): [1, 2]
Push C (3): [1, 2, 3]
Encounter +: Pop 3 and 2 → 2 + 3 = 5; Stack: [1, 5]
Encounter *: Pop 5 and 1 → 1 * 5 = 5; Stack: [5]
Push C (3): [5, 3]
Push B (2): [5, 3, 2]
Push A (1): [5, 3, 2, 1]
Encounter –: Pop 1 and 2 → 2 - 1 = 1; Stack: [5, 3, 1]
Encounter +: Pop 1 and 3 → 3 + 1 = 4; Stack: [5, 4]
Encounter *: Pop 4 and 5 → 5 * 4 = 20; Stack: [20]
Final Result: 20
Summary:
1. A B + C – B A + C - + evaluates to 0.
2. A B C + * C B A - + * evaluates to 20.
Answer:
Merge Sort: A sorting algorithm that divides the data into two halves, recursively sorts each half,
and then merges the sorted halves back together.
Quick Sort: A sorting algorithm that selects a pivot element, partitions the data around the pivot, and
recursively sorts the subarrays.
Answer:
1. Choose Pivot: Choose a pivot element from the array. For simplicity, let's choose the last element as
the pivot.
o Initial Array: [42, 29, 74, 11, 65, 58]
o Pivot: 58
2. Partitioning: Rearrange the elements such that elements smaller than the pivot go to the left, and
elements greater than the pivot go to the right. After partitioning:
o [42, 29, 11, 58, 65, 74]
3. Recursively Apply Quick Sort on the subarrays to the left and right of the pivot:
o Left Subarray: [42, 29, 11]
Pivot: 11
After partitioning: [11, 29, 42]
o Right Subarray: [65, 74]
Pivot: 74
After partitioning: [65, 74]
4. Final Sorted Array: [11, 29, 42, 58, 65, 74]
Ques 3: Write a C Program for Insertion Sort and Discuss Its Efficiency
Answer:
#include <stdio.h>
// Move elements of arr[0..i-1], that are greater than key, to one position ahead
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
int main() {
int arr[] = {42, 29, 74, 11, 65, 58};
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
return 0;
}
#include <stdio.h>
int main() {
int arr[] = {42, 29, 74, 11, 65, 58};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
return 0;
}
#include <stdio.h>
int main() {
int arr[] = {42, 29, 74, 11, 65, 58};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
return 0;
}
#include <stdio.h>
int main() {
int arr[] = {42, 29, 74, 11, 65, 58};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n-1);
return 0;
}
Ques 7: Write an Algorithm/C Function to Implement Merge Sort
Answer:
#include <stdio.h>
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (leftArr[i] <= rightArr[j]) {
arr[k] = leftArr[i];
i++;
} else {
arr[k] = rightArr[j];
j++;
}
k++;
}
int main() {
int arr[] = {42, 29, 74, 11, 65, 58};
int n = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, n-1);
return 0;
}
Ques 8: Using Quick Sort, Give Tracing for the Following Set of Numbers
Answer:
Tracing Steps:
1. First Pass:
Pivot: 99, Partitioning: [42, 11, 23, 58, 65, 72, 36, 99]
2. Second Pass (Left subarray, Pivot = 72):
Partitioning: [42, 11, 23, 58, 65, 36, 72, 99]
3. Third Pass (Left subarray, Pivot = 36):
Partitioning: [11, 23, 36, 58, 65, 42]
4. Continue recursively to partition and sort.
The final sorted array: [11, 23, 36, 42, 58, 65, 72, 99]
Searching
Ques 1: Precondition and Algorithm of Binary Search Method
Answer:
Precondition:
Answer:
Ques 2: Write an algorithm to implement ascending priority queue using a singly linked list.
Answer:
An ascending priority queue means elements are inserted in such a way that the list is always ordered from
lowest to highest priority (or value).
insert():
struct Node {
int data;
struct Node *next;
};
newNode->next = current->next;
current->next = newNode;
}
Answer:
Ques 4: Write a program to insert and delete an element after a given node in a singly linked list.
Answer:
1. Find the node after which the new node will be inserted.
2. Create a new node with the given data.
3. Adjust the pointers to insert the new node after the given node.
To represent a polynomial, each node in the doubly linked list will store the coefficient and the exponent of
a term.
Steps:
struct PolyNode {
int coef;
int exp;
struct PolyNode *next;
struct PolyNode *prev;
};
temp->next = NULL;
temp->prev = tail;
if (tail != NULL) tail->next = temp;
tail = temp;
return result;
}
Answer:
To concatenate two doubly linked lists:
temp->next = list2;
if (list2 != NULL) list2->prev = temp;
}
Ques 3: Explain the advantages of doubly linked list over singly linked list.
Answer:
Advantages:
1. Bidirectional Traversal: Doubly linked lists can be traversed in both forward and backward
directions, unlike singly linked lists, which can only be traversed in one direction.
2. Efficient Deletion: Insertion and deletion at both ends are more efficient. In a singly linked list,
deleting a node requires knowledge of the previous node, while in a doubly linked list, the previous
pointer is already available.
3. More Flexible: Doubly linked lists allow more complex operations such as reversing a list or
inserting/deleting nodes at any position with fewer pointer manipulations.
Ques 4: Write function delete(p, &x) which deletes the node pointed by p in a doubly linked list.
Answer:
if (p->prev != NULL) {
p->prev->next = p->next;
}
if (p->next != NULL) {
p->next->prev = p->prev;
}
Ques 1: State the advantages of circular and doubly linked lists over singly linked lists.
Answer:
Efficient Traversal: Can be traversed in a circular manner, allowing easy access to the first node
from the last node without needing a special reference.
Simplified Operations: Insertion and deletion at both ends become more straightforward as the list
is circular and does not require special handling for the first and last elements.
Bidirectional Traversal: Can traverse in both directions, unlike singly linked lists.
Efficient Deletion: Insertion and deletion operations are more efficient as there is direct access to the
previous node.
Ques 2: Write an algorithm to perform operations on Circular Singly Linked List using a header
node:
Answer:
1. Traverse to the last node (where the next pointer points to the header).
2. Insert the new node after the last node and make it point to the header node.
1. Create a new node and make it point to the node that the header node points to.
2. Update the header node to point to the new node.
newNode->next = header;
temp->next = newNode;
}
void addNodeAtBeginning(struct Node *header, int data) {
struct Node *newNode = (struct Node*) malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = header->next;
header->next = newNode;
}
TREE
Ques 1: Discuss the following with reference to trees:
Answer:
Tree: A tree is a non-linear hierarchical data structure consisting of nodes connected by edges. It has
a root node, from which all other nodes branch out, where each node has one parent, and may have
multiple child nodes.
Node: A node is a fundamental unit of a tree, containing data and pointers to its child nodes.
Parent Node: A parent node is a node that has one or more child nodes. It is linked to the child
nodes by edges.
Child Node: A child node is a node that has a parent and is connected by an edge from the parent
node.
Link: A link is the reference or pointer from a parent node to a child node, representing the
relationship between the nodes.
Root: The root is the topmost node in a tree and does not have any parent. All other nodes in the tree
are descendants of the root.
Leaf: A leaf node is a node that has no children. It is the terminal node in a tree.
Level: The level of a node is the number of edges from the root node to the given node. The root is at
level 0.
Height: The height of a tree is the length of the longest path from the root to any leaf node. It is also
the level of the deepest node in the tree.
Degree: The degree of a node is the number of children it has. It is the number of direct descendants
of a node.
Binary Tree: A binary tree is a tree in which each node has at most two children, referred to as the
left child and the right child.
Complete Binary Tree: A complete binary tree is a binary tree in which all levels, except possibly
the last, are completely filled, and all nodes are as far left as possible.
Strictly Binary Tree: A strictly binary tree is a binary tree in which every node has either two
children or no children.
Threaded Binary Tree: A threaded binary tree is a binary tree where the null pointers are replaced
by pointers to the next node in the in-order traversal, allowing faster traversal.
Forest: A forest is a collection of disjoint trees. It can be formed by deleting the root of a tree,
resulting in multiple smaller trees.
Sibling: Siblings are nodes that share the same parent in a tree.
Binary Search Tree (BST): A binary search tree is a binary tree where for every node, the left
subtree contains only nodes with keys less than the node’s key, and the right subtree contains only
nodes with keys greater than the node’s key.
Height Balanced Tree (AVL Tree): An AVL tree is a self-balancing binary search tree where the
difference between the heights of the left and right subtrees of every node is at most 1.
Almost Complete Binary Tree: An almost complete binary tree is a binary tree where all levels are
completely filled, except possibly the last level, which is filled from left to right.
Full Binary Tree: A full binary tree is a binary tree in which every node has either 0 or 2 children.
Answer:
Hierarchical Data Representation: Trees are used to represent hierarchical data such as file
systems, organization structures, and XML/HTML documents.
Search Operations: Binary Search Trees (BSTs) are used for efficient searching, insertion, and
deletion operations in databases.
Network Routing: Trees are used in network routing algorithms like spanning trees for optimal
routing in networks.
Expression Parsing: Trees are used in compilers to parse and evaluate expressions, especially in
abstract syntax trees.
Game Trees: In game theory, trees represent possible moves in games like chess or tic-tac-toe,
where each node represents a game state.
Decision Making: Trees are used in decision-making algorithms (decision trees) for classification
and regression problems in machine learning.
Ques 3: Construct a tree for the given inorder and postorder traversals:
Answer:
Step-by-step construction:
1. The root node is the last node of the postorder traversal, which is A.
2. Split the inorder traversal at A:
Left subtree: DGB
Right subtree: HEICF
3. The next root node from the postorder traversal is C, which is the last element of the right subtree in
postorder.
4. Split the right subtree of the inorder traversal at C:
Left subtree: HEI
Right subtree: F
5. Repeat the same process for the subtrees:
o For the left subtree of C, the root is E.
o For the right subtree of C, the root is F.
6. Similarly, for the left subtree of A, the root is B. Split DGBA into left (D) and right (GB), and then
process recursively.
A
/ \
B C
/\ / \
D G E F
/ \
H I
Answer:
Binary Tree:
F
/ \
B G
/\ \
A D I
/\ /
C E H
Traversal Results:
F, B, A, D, C, E, G, I, H
A, B, C, D, E, F, G, H, I
Answer:
10
/ \
3 15
\ \
6 22
\ \
5 45
/ \
23 65
/ / \
34 78
Ques 6: Define height of the binary tree and height balanced tree:
Answer:
Height of a Binary Tree: The height of a binary tree is the number of edges on the longest path
from the root to a leaf node.
Height Balanced Tree: A height-balanced tree (AVL tree) is a binary search tree where the
difference in heights of the left and right subtrees of every node is at most 1.
Advantages:
Improved search, insertion, and deletion efficiency as the tree remains balanced, ensuring
logarithmic time complexity (O(log n)).
Ques 7: Construct a height balanced binary tree (AVL tree) for the following data:
Answer:
Data: 32, 16, 44, 52, 78, 40, 12, 22, 02, 23
44
/ \
32 52
/ \ / \
16 40 23 78
/ /
2 22
Ques 8: Why is a Threaded Binary Tree required? Draw a right in threaded binary tree for the given fig.1.
Answer:
Definition:
A Threaded Binary Tree is a binary tree in which the null pointers (typically in the left and/or right child
of leaf nodes) are replaced with "threads." These threads point to the next node in a specific traversal order,
typically the in-order traversal. The threads allow for efficient traversal without the need for recursion or
stack-based mechanisms.
In a single-threaded binary tree, the null right child pointers are replaced with threads that point to
the in-order successor of the node.
In a double-threaded binary tree, both left and right null child pointers are replaced with threads
that point to the in-order predecessor (left thread) and in-order successor (right thread).
Why It Is Required:
A
/ \
B E
/\ /\
C DF H
\
G
C→B→D→A→F→G→E→H
A
/ \
B E
/\ /\
C DF H
\ \ \
B A E
/
G
Ques 9: Write an Algorithm to Perform Traversal of Binary Search Tree (BST)
Answer:
Preorder Traversal Algorithm
Ques 10: Define an AVL tree. Obtain an AVL tree by inserting one integer at a time in the following
sequence. 150, 155, 160, 115, 110, 140, 120, 145, 130, 147, 170, 180. Show all the steps
Answer:
An AVL Tree (Adelson-Velsky and Landis Tree) is a self-balancing Binary Search Tree (BST) where the
difference in height between the left and right subtrees of any node is at most 1. This balance is maintained
through rotations. If the tree becomes unbalanced after an insertion, rotations are performed to restore
balance.
Balance Factor: The difference in height between the left and right subtrees of a node. If the balance
factor of a node becomes greater than 1 or less than -1, the tree is unbalanced, and rotations are
performed to restore balance.
Rotations: To restore balance, left rotations, right rotations, and combinations of both (left-right
and right-left) are used.
Insertion Sequence:
We will insert the integers in the following sequence: 150, 155, 160, 115, 110, 140, 120, 145, 130, 147, 170,
180.
150
2. Insert 155
150
\
155
3. Insert 160
160 is greater than both 150 and 155, so it becomes the right child of 155.
The balance factor of 150 becomes -2 (left height = 0, right height = 2), so the tree is unbalanced.
Right-Right Case: Perform a left rotation at node 150.
155
/ \
150 160
4. Insert 115
115 is less than 155 and less than 150, so it becomes the left child of 150.
No rotation needed because the tree remains balanced.
155
/ \
150 160
/
115
5. Insert 110
110 is less than 115 and 150, so it becomes the left child of 115.
No rotation needed because the tree remains balanced.
155
/ \
150 160
/
115
/
110
6. Insert 140
140 is less than 155 but greater than 115, so it becomes the right child of 115.
No rotation needed because the tree remains balanced.
155
/ \
150 160
/
115
/ \
110 140
7. Insert 120
120 is greater than 115 but less than 140, so it becomes the left child of 140.
No rotation needed because the tree remains balanced.
155
/ \
150 160
/
115
/ \
110 140
/
120
8. Insert 145
145 is greater than 140 but less than 150, so it becomes the right child of 140.
No rotation needed because the tree remains balanced.
155
/ \
150 160
/
115
/ \
110 140
/ \
120 145
9. Insert 130
130 is greater than 115 but less than 140, so it becomes the left child of 140.
The balance factor of 150 becomes 2, indicating an imbalance (left-heavy).
Left-Right Case: Perform a left rotation on 140, followed by a right rotation on 150.
markdown
Copy code
155
/ \
130 160
/ \
115 150
/ \ \
110 120 145
10. Insert 147
147 is greater than 145 but less than 150, so it becomes the right child of 145.
No rotation needed because the tree remains balanced.
155
/ \
130 160
/ \
115 150
/ \ \
110 120 145
\
147
11. Insert 170
155
/ \
130 160
/ \ \
115 150 170
/ \ \
110 120 145
\
147
12. Insert 180
155
/ \
130 170
/ \ / \
115 150 160 180
/ \ \
110 120 145
\
147
Final AVL Tree:
155
/ \
130 170
/ \ / \
115 150 160 180
/ \ \
110 120 145
\
147