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

data structure

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

data structure

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

i) What is a Stack? Give the implementation of a stack.

A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. This means that
the last element added to the stack will be the first one to be removed. Think of it like a stack of
plates: you add plates to the top and also remove them from the top.
Here's a simple implementation of a stack in C:
c
#include <stdio.h>
#define MAX 10

int stack[MAX];
int top = -1;

void push(int value) {


if (top == MAX - 1) {
printf("Stack Overflow\n");
} else {
top++;
stack[top] = value;
}
}

int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
} else {
int value = stack[top];
top--;
return value;
}
}

int main() {
push(10);
push(20);
printf("Popped value: %d\n", pop());
return 0;
}
ii) What is Structured Programming?
Structured programming is a programming paradigm aimed at improving the clarity, quality, and
development time of a computer program by making extensive use of subroutines, block structures,
for and while loops, and other constructs. It emphasizes breaking down a program into smaller,
manageable sections or modules, each with a single entry and exit point. This approach helps in
writing clear, understandable, and maintainable code.
iii) What are Primitive and Non-Primitive Data Structures?
Primitive Data Structures: These are the basic data types provided by a programming language.
Examples include integers, floats, characters, and pointers. They are the building blocks for data
manipulation.
Non-Primitive Data Structures: These are more complex data structures that are derived from
primitive data structures. They include arrays, linked lists, stacks, queues, trees, and graphs. Non-
primitive data structures are used to store and manage data in a more sophisticated way.
iv) Differentiate between Linked List and Array
 Memory Allocation: Arrays have a fixed size and use contiguous memory locations, while
linked lists are dynamic and use non-contiguous memory locations.
 Access Time: Arrays provide O(1) time complexity for accessing elements, whereas linked
lists have O(n) time complexity.
 Insertion/Deletion: Inserting or deleting elements in an array is costly (O(n)), while in linked
lists, it is more efficient (O(1) if the pointer is known).
 Memory Utilization: Arrays can lead to memory wastage if the allocated space is not fully
utilized, whereas linked lists use memory more efficiently as they grow and shrink
dynamically.
v) Applications of Linked List
 Dynamic Memory Allocation: Linked lists are used in scenarios where the size of the data
structure is not known in advance.
 Implementation of Data Structures: They are used to implement other data structures like
stacks, queues, and graphs.
 Efficient Insertion/Deletion: Useful in applications where frequent insertion and deletion of
elements are required.
 Memory Management: Linked lists are used in memory management systems to keep track
of free and used memory blocks.
vi) Differentiate between Recursion and Iteration
 Definition: Recursion is a process where a function calls itself, while iteration is a process
where a set of instructions is repeated until a condition is met.
 Memory Usage: Recursion uses more memory due to function call stack, whereas iteration
uses less memory.
 Performance: Iteration is generally faster and more efficient than recursion.
 Complexity: Recursion can lead to simpler and more readable code for problems that have a
recursive nature, while iteration can be more complex but is often more efficient.
vii) Difference between Single Dimension Array and Two Dimension Array
 Structure: A single dimension array is a list of elements, whereas a two-dimensional array is
an array of arrays (a matrix).
 Access: Elements in a single dimension array are accessed using a single index, while
elements in a two-dimensional array are accessed using two indices.
 Usage: Single dimension arrays are used for linear data storage, while two-dimensional
arrays are used for tabular data storage, such as matrices and tables.
viii) Why Underflow Condition Comes in Any Data Structure?
Underflow occurs when an attempt is made to remove an element from an empty data structure.
This can happen in stacks, queues, and other data structures when there are no elements to remove.
It indicates that the data structure is empty and no further removal operations can be performed
until new elements are added.
I hope this helps! If you have any more questions or need further clarification, feel free to ask.
ix) Difference between Constants and Variables
 Constants: Constants are fixed values that do not change during the execution of a program.
They are defined using the const keyword in many programming languages. For example,
const int MAX = 100; defines a constant integer with a value of 100.
 Variables: Variables are storage locations that can hold different values during the execution
of a program. They are defined using variable declaration syntax, such as int x = 10;. The
value of a variable can be changed throughout the program.
x) Applications of Stack
1. Expression Evaluation: Stacks are used to evaluate expressions (infix, postfix, and prefix). For
example, converting an infix expression (like A + B) to a postfix expression (like AB+) and then
evaluating it using a stack.
2. Backtracking: Stacks are used in algorithms that involve backtracking, such as maze solving
and parsing. For example, in a maze-solving algorithm, the stack can be used to keep track of
the path taken and backtrack when a dead end is reached.
xi) Sequential Search Algorithm
c
int sequentialSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i; // Key found at index i
}
}
return -1; // Key not found
}
xii) Method for Conversion from Infix to Postfix Notation
1. Initialize an empty stack and an empty postfix expression.
2. Scan the infix expression from left to right.
3. If the scanned character is an operand, add it to the postfix expression.
4. If the scanned character is an operator, pop from the stack to the postfix expression until the
stack is empty or the top of the stack has less precedence than the scanned operator. Push
the scanned operator to the stack.
5. If the scanned character is '(', push it to the stack.
6. If the scanned character is ')', pop from the stack to the postfix expression until '(' is
encountered.
7. Pop all the remaining operators from the stack to the postfix expression.
xiii) Explain Pop Operation of Stack. Write an Algorithm of this Operation.
The pop operation removes the top element from the stack.
Algorithm:
1. Check if the stack is empty.
2. If the stack is empty, return an error message.
3. If the stack is not empty, remove the top element and return it.
c
int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
} else {
int value = stack[top];
top--;
return value;
}
}
xiv) What is a Tree? What is Height and Path of a Tree? Explain with Example.
A tree is a hierarchical data structure consisting of nodes, with a single node as the root and zero or
more child nodes. Each child node can have zero or more child nodes, and so on.
 Height: The height of a tree is the length of the longest path from the root to a leaf node.
 Path: A path in a tree is a sequence of nodes from one node to another.
Example:
A
/\
B C
/\ \
D E F
 The height of this tree is 2 (A -> B -> D).
 A path example is A -> C -> F.
xv) What is Sorting? Write an Algorithm for Insertion Sort
Sorting is the process of arranging data in a specific order, typically in ascending or descending order.
Sorting is a fundamental operation in computer science and is used in various applications such as
searching, data analysis, and database management.
Insertion Sort is a simple and intuitive sorting algorithm that builds the final sorted array one item at
a time. It is much like sorting playing cards in your hands. The algorithm divides the array into a
sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct
position in the sorted part.
Algorithm for Insertion Sort:
1. Start with the second element (index 1) as the key.
2. Compare the key with the elements before it.
3. If the key is smaller than the compared element, shift the compared element one position to
the right.
4. Repeat step 3 until the key is larger than the compared element or you reach the beginning
of the array.
5. Insert the key at the correct position.
6. Move to the next element and repeat steps 2-5 until the entire array is sorted.
Here is the pseudocode for Insertion Sort:
c
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;

// Move elements of arr[0..i-1], that are greater than key,


// to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
Q.3 What is Selection Sort? Explain its Working by Taking a Suitable Example.
Selection Sort is a simple comparison-based sorting algorithm. It works by repeatedly selecting the
smallest (or largest, depending on the order) element from the unsorted portion of the array and
moving it to the sorted portion.
Working Example: Consider the array: [64, 25, 12, 22, 11]
1. First Pass:
o Find the smallest element in the array (11).
o Swap it with the first element.
o Array becomes: [11, 25, 12, 22, 64]
2. Second Pass:
o Find the smallest element in the remaining array (12).
o Swap it with the second element.
o Array becomes: [11, 12, 25, 22, 64]
3. Third Pass:
o Find the smallest element in the remaining array (22).
o Swap it with the third element.
o Array becomes: [11, 12, 22, 25, 64]
4. Fourth Pass:
o Find the smallest element in the remaining array (25).
o Swap it with the fourth element.
o Array becomes: [11, 12, 22, 25, 64]
5. Fifth Pass:
o The array is already sorted.
Q.4 What Do You Mean by Sequential and Linked Representation of Binary Tree in Memory?
Explain.
Sequential Representation:
 In sequential representation, a binary tree is stored in an array.
 The root node is stored at index 0.
 For any node at index i, its left child is stored at index 2i + 1 and its right child is stored at
index 2i + 2.
 This representation is efficient for complete binary trees but can waste space for sparse
trees.
Linked Representation:
 In linked representation, each node of the binary tree is represented by a structure
containing data and pointers to its left and right children.
 This representation is more flexible and efficient for sparse trees as it does not waste space.
Example:
c
struct Node {
int data;
struct Node* left;
struct Node* right;
};
Q.5 List Various Operations Associated with Linked List.
1. Insertion: Adding a new node to the linked list.
o At the beginning
o At the end
o After a given node
2. Deletion: Removing a node from the linked list.
o From the beginning
o From the end
o After a given node
3. Traversal: Accessing each node of the linked list to perform some operation.
4. Searching: Finding a node with a given value.
5. Updating: Changing the value of a node.
Q.6 Write an Algorithm to Delete an Element in a Linear Array.
Algorithm:
1. Start.
2. Input the array elements and the element to be deleted.
3. Find the position of the element to be deleted.
4. Shift all elements after the position to the left by one position.
5. Decrease the size of the array by one.
6. End.
Example:
c
void deleteElement(int arr[], int n, int key) {
int pos = -1;
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
pos = i;
break;
}
}
if (pos == -1) {
printf("Element not found\n");
return;
}
for (int i = pos; i < n - 1; i++) {
arr[i] = arr[i + 1];
}
n--;
}
Q.7 Explain How You Will Insert an Element into a Binary Search Tree.
Algorithm:
1. Start.
2. If the tree is empty, create a new node and make it the root.
3. Otherwise, compare the element with the root.
4. If the element is smaller than the root, recursively insert it into the left subtree.
5. If the element is larger than the root, recursively insert it into the right subtree.
6. End.
Example:
c
struct Node* insert(struct Node* node, int key) {
if (node == NULL) {
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = key;
temp->left = temp->right = NULL;
return temp;
}
if (key < node->data) {
node->left = insert(node->left, key);
} else if (key > node->data) {
node->right = insert(node->right,
Q.23 Explain the Various Types of Data Structures (CO-1)
Data structures can be broadly classified into two categories:
1. Primitive Data Structures: These are the basic data types provided by a programming
language. Examples include integers, floats, characters, and pointers.
2. Non-Primitive Data Structures: These are more complex data structures that are derived
from primitive data structures. They include:
o Arrays: A collection of elements identified by index or key.
o Linked Lists: A linear collection of data elements where each element points to the
next.
o Stacks: A collection of elements that follows the Last In, First Out (LIFO) principle.
o Queues: A collection of elements that follows the First In, First Out (FIFO) principle.
o Trees: A hierarchical structure with a root node and child nodes.
o Graphs: A collection of nodes connected by edges.
Q.27 Define Array. Give Algorithm for Traversing an Array (CO-2)
An array is a collection of elements, each identified by an array index or key. Arrays are used to store
multiple values in a single variable.
Algorithm for Traversing an Array:
1. Start.
2. Initialize the array and its size.
3. Loop through the array from the first element to the last.
4. Access and process each element.
5. End.
Example:
c
void traverseArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
}
Q.24 Give Five Differences Between an Array and a Linked List (CO-2)
1. Memory Allocation: Arrays have a fixed size and use contiguous memory locations, while
linked lists are dynamic and use non-contiguous memory locations.
2. Access Time: Arrays provide O(1) time complexity for accessing elements, whereas linked
lists have O(n) time complexity.
3. Insertion/Deletion: Inserting or deleting elements in an array is costly (O(n)), while in linked
lists, it is more efficient (O(1) if the pointer is known).
4. Memory Utilization: Arrays can lead to memory wastage if the allocated space is not fully
utilized, whereas linked lists use memory more efficiently as they grow and shrink
dynamically.
5. Data Structure Type: Arrays are static data structures, while linked lists are dynamic data
structures.
Q.28 Give Algorithm for Deleting an Element from the Stack (CO-4)
Algorithm:
1. Start.
2. Check if the stack is empty.
3. If the stack is empty, return an error message.
4. If the stack is not empty, remove the top element and return it.
5. End.
Example:
c
int pop(int stack[], int *top) {
if (*top == -1) {
printf("Stack Underflow\n");
return -1;
} else {
int value = stack[*top];
(*top)--;
return value;
}
}
Q.25 Explain Linear and Non-Linear Data Structures (CO-1)
 Linear Data Structures: In linear data structures, elements are arranged in a sequential
manner. Each element is connected to its previous and next element. Examples include
arrays, linked lists, stacks, and queues.
 Non-Linear Data Structures: In non-linear data structures, elements are not arranged in a
sequential manner. Each element can be connected to multiple elements, forming a
hierarchical structure. Examples include trees and graphs.
Q26) Algorithm for Adding an Element at the Beginning of a Linked List
1. Create a New Node: Allocate memory for the new node and assign the data to it.
2. Point New Node to Head: Set the next pointer of the new node to point to the current head
of the linked list.
3. Update Head: Update the head of the linked list to be the new node.
Example:
c
#include <stdio.h>
#include <stdlib.h>

// Define the structure of a node


struct Node {
int data;
struct Node* next;
};

// Function to add a new node at the beginning


void addAtBeginning(struct Node** head_ref, int new_data) {
// Allocate memory for the new node
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

// Assign data to the new node


new_node->data = new_data;

// Point the new node to the current head


new_node->next = (*head_ref);

// Update the head to be the new node


(*head_ref) = new_node;
}

// Function to print the linked list


void printList(struct Node* node) {
while (node != NULL) {
printf("%d -> ", node->data);
node = node->next;
}
printf("NULL\n");
}

int main() {
// Start with an empty list
struct Node* head = NULL;

// Add elements to the list


addAtBeginning(&head, 10);
addAtBeginning(&head, 20);
addAtBeginning(&head, 30);

// Print the list


Q.34 Explain Sequential Search Technique with Suitable Example? Give Algorithm. (CO-6)
Sequential Search (also known as Linear Search) is a straightforward search algorithm that checks
each element in a list one by one until the desired element is found or the list ends. It is simple to
implement but can be inefficient for large lists.
Example: Consider an array: [5, 3, 8, 4, 2]
To find the element 4 using sequential search:
1. Start from the first element (5). It is not 4.
2. Move to the next element (3). It is not 4.
3. Move to the next element (8). It is not 4.
4. Move to the next element (4). It is 4. The search is successful.
Algorithm:
1. Start.
2. Initialize the array and the element to be searched.
3. Loop through the array from the first element to the last.
4. Compare each element with the search element.
5. If a match is found, return the index of the element.
6. If no match is found, return -1.
7. End.
Pseudocode:
c
int sequentialSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i; // Key found at index i
}
}
return -1; // Key not found
}
Explanation:
 The function sequentialSearch takes an array arr, its size n, and the search key key as inputs.
 It iterates through the array using a for loop.
 For each element, it checks if the element matches the search key.
 If a match is found, it returns the index of the element.
 If no match is found after checking all elements, it returns -1.
Time Complexity:
 Best Case: O(1) (when the element is found at the first position)
 Worst Case: O(n) (when the element is not found or is at the last position)
Sequential search is useful for small or unsorted lists where the overhead of more complex
algorithms is not justified.
I hope this helps! If you have any more questions or need further clarification, feel free to ask.
Q.33 What are different types of Arrays? Explain how element of arrays are stored in memory?
Q.33 What are Different Types of Arrays? Explain How Elements of Arrays are Stored in Memory.
Types of Arrays:
1. Single-Dimensional Array: Also known as a one-dimensional array, it is a linear array where
elements are stored in a single row. Example: int arr[5] = {1, 2, 3, 4, 5};
2. Multi-Dimensional Array: Arrays that have more than one dimension. The most common
type is the two-dimensional array, which can be visualized as a matrix.
o Two-Dimensional Array: Elements are stored in a table with rows and columns.
Example: int arr[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
o Three-Dimensional Array: Elements are stored in a 3D space, like a cube. Example:
int arr[2][2][2] = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};
Storage of Array Elements in Memory:
 Single-Dimensional Array: Elements are stored in contiguous memory locations. The address
of each element can be calculated using the base address and the index. For an array arr
with base address BA, the address of the element at index i is calculated as:
Address(arr[i])=BA+i×size_of_element\text{Address}(arr[i]) = BA + i \times \text{size\_of\_element}
 Two-Dimensional Array: Elements can be stored in either row-major or column-major order.
o Row-Major Order: Elements of each row are stored in contiguous memory locations.
The address of the element at row i and column j in a 2D array arr with base address
BA and n columns is calculated as:
Address(arr[i][j])=BA+((i×n)+j)×size_of_element\text{Address}(arr[i][j]) = BA + ((i \times n) + j) \times
\text{size\_of\_element}
 Column-Major Order: Elements of each column are stored in contiguous memory locations.
The address of the element at row i and column j in a 2D array arr with base address BA and
m rows is calculated as:
Address(arr[i][j])=BA+((j×m)+i)×size_of_element\text{Address}(arr[i][j]) = BA + ((j \times m) + i)
\times \text{size\_of\_element}
Example: Consider a 2D array arr[2][3] stored in row-major order:
arr[2][3] = {{1, 2, 3}, {4, 5, 6}}
Memory layout:
123456
The address of arr[1][2] (which is 6) can be calculated as:
Address(arr[1][2])=BA+((1×3)+2)×size_of_e

Q.27 Write an Algorithm to PUSH an Element into the Stack (CO1)


Algorithm:
1. Start.
2. Check if the stack is full.
3. If the stack is full, return an error message (Stack Overflow).
4. If the stack is not full, increment the top pointer.
5. Add the element to the position pointed by the top.
6. End.
Example:
c
void push(int stack[], int *top, int max, int value) {
if (*top == max - 1) {
printf("Stack Overflow\n");
} else {
(*top)++;
stack[*top] = value;
}
}
Q.29 When Does Underflow Condition Come in Data Structure? (CO3)
Underflow occurs when an attempt is made to remove an element from an empty data structure.
This can happen in stacks, queues, and other data structures when there are no elements to remove.
It indicates that the data structure is empty and no further removal operations can be performed
until new elements are added.
Q.25 Differentiate Between Stack and Queue (CO3)
 Definition:
o Stack: A stack is a linear data structure that follows the Last In, First Out (LIFO)
principle. The last element added to the stack is the first one to be removed.
o Queue: A queue is a linear data structure that follows the First In, First Out (FIFO)
principle. The first element added to the queue is the first one to be removed.
 Operations:
o Stack: The primary operations are push (to add an element) and pop (to remove an
element).
o Queue: The primary operations are enqueue (to add an element) and dequeue (to
remove an element).
 Usage:
o Stack: Used in scenarios like expression evaluation, backtracking algorithms, and
function call management.
o Queue: Used in scenarios like scheduling processes, managing tasks in a printer
queue, and breadth-first search in graphs.
 Access:
o Stack: Only the top element can be accessed directly.
o Queue: Only the front element can be accessed directly.
 Example:
o Stack: Think of a stack of plates where you can only add or remove the top plate.
o Queue: Think of a line of people where the first person in line is the first to be
served.
Q.26 Differentiate Between Prefix and Postfix Expression (CO3)
 Definition:
o Prefix Expression: Also known as Polish notation, the operator precedes its
operands. For example, the prefix expression for (A + B) * C is * + A B C.
o Postfix Expression: Also known as Reverse Polish notation, the operator follows its
operands. For example, the postfix expression for (A + B) * C is A B + C *.
 Evaluation:
o Prefix Expression: Evaluation starts from the rightmost operator and moves left.
Operands are pushed onto a stack, and operators pop operands from the stack,
perform the operation, and push the result back onto the stack.
o Postfix Expression: Evaluation starts from the leftmost operand and moves right.
Operands are pushed onto a stack, and operators pop operands from the stack,
perform the operation, and push the result back onto the stack.
 Usage:
o Prefix Expression: Less common in programming but used in certain mathematical
and logical expressions.
o Postfix Expression: Commonly used in stack-based calculations and expression
evaluation in compilers.
 Example:
o Prefix Expression: For the expression (A - B) / (C + D), the prefix notation is / - A B + C
D.
o Postfix Expression: For the expression (A - B) / (C + D), the postfix notation is A B - C
D + /.
Q.28 Write a Program to Print Factorial of a Number Using Recursion
Example:
c
#include <stdio.h>

// Function to calculate factorial using recursion


int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}

int main() {
int num = 5;
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
In this example, the factorial function calculates the factorial of a number using recursion. The base
case is when n is 0, and the recursive case multiplies n by the factorial of n-1.
Q.33 Explain in Detail Various Operations Associated with Linked List (CO3)
Linked lists are dynamic data structures that consist of nodes. Each node contains data and a
reference (or link) to the next node in the sequence. Here are the primary operations associated with
linked lists:
1. Insertion:
o At the Beginning: Add a new node at the start of the list.
o At the End: Add a new node at the end of the list.
o After a Given Node: Add a new node after a specified node in the list.
2. Deletion:
o From the Beginning: Remove the first node of the list.
o From the End: Remove the last node of the list.
o After a Given Node: Remove a node after a specified node in the list.
3. Traversal: Access each node of the linked list to perform some operation (e.g., printing the
data).
4. Searching: Find a node with a given value.
5. Updating: Change the value of a node.
Q.34 Write a Program in C for Multiplication of Two Matrices (CO1)
Here's a simple C program to multiply two matrices:
c
#include <stdio.h>

void multiplyMatrices(int firstMatrix[][10], int secondMatrix[][10], int result[][10], int rowFirst, int
columnFirst, int rowSecond, int columnSecond) {
for (int i = 0; i < rowFirst; ++i) {
for (int j = 0; j < columnSecond; ++j) {
result[i][j] = 0;
for (int k = 0; k < columnFirst; ++k) {
result[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}
}

int main() {
int firstMatrix[10][10], secondMatrix[10][10], result[10][10];
int rowFirst, columnFirst, rowSecond, columnSecond;

printf("Enter rows and columns for the first matrix: ");


scanf("%d %d", &rowFirst, &columnFirst);

printf("Enter rows and columns for the second matrix: ");


scanf("%d %d", &rowSecond, &columnSecond);

if (columnFirst != rowSecond) {
printf("Error! Column of the first matrix should be equal to row of the second matrix.\n");
return -1;
}

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


for (int i = 0; i < rowFirst; ++i) {
for (int j = 0; j < columnFirst; ++j) {
scanf("%d", &firstMatrix[i][j]);
}
}

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


for (int i = 0; i < rowSecond; ++i) {
for (int j = 0; j < columnSecond; ++j) {
scanf("%d", &secondMatrix[i][j]);
}
}

multiplyMatrices(firstMatrix, secondMatrix, result, rowFirst, columnFirst, rowSecond,


columnSecond);

printf("Resultant matrix:\n");
for (int i = 0; i < rowFirst; ++i) {
for (int j = 0; j < columnSecond; ++j) {
printf("%d ", result[i][j]);
}
printf("\n");
}

return 0;
}
Q.35 Discuss the Quick Sort Algorithm with an Example (CO6)
Quick Sort is a highly efficient sorting algorithm that uses the divide-and-conquer approach. 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.
Algorithm:
1. Choose a pivot element from the array.
2. Partition the array into two sub-arrays: elements less than the pivot and elements greater
than the pivot.
3. Recursively apply the above steps to the sub-arrays.
4. Combine the sorted sub-arrays and the pivot to get the final sorted array.
Example: Consider the array: [10, 7, 8, 9, 1, 5]
1. Choose the pivot (e.g., 5).
2. Partition the array: [1, 5, 7, 8, 9, 10]
3. Recursively apply quick sort to the sub-arrays [1] and [7, 8, 9, 10].
4. Combine the sorted sub-arrays and the pivot to get the final sorted array: [1, 5, 7, 8, 9, 10].
Q.36 Write Short Note on the Following (CO3)
(a) Doubly Linked List
A doubly linked list is a type of linked list in which each node contains a data part and two pointers:
one pointing to the next node and one pointing to the previous node. This allows traversal of the list
in both directions (forward and backward).
Advantages:
 Easier to delete a given node without traversing the list from the head.
 Can be traversed in both directions.
Disadvantages:
 Requires more memory for the additional pointer.
 More complex insertion and deletion operations compared to a singly linked list.
(b) Application of Queues
Queues are used in various applications where elements need to be processed in the order they
arrive. Some common applications include:
 CPU Scheduling: Managing processes in an operating system.
 Printer Queue: Managing print jobs in a printer.
 Breadth-First Search (BFS): Traversing graphs and trees.
 Customer Service Systems: Managing customers in a service line.
Q.28 Give inorder, postorder and preorder traversal of the following tree.
To provide the inorder, postorder, and preorder traversal of a binary tree, I need to see the structure
of the tree. Since the tree structure isn't provided in your message, I'll explain the traversal methods
using a sample binary tree:
A
/\
B C
/\ \
D E F
Inorder Traversal (Left, Root, Right)
1. Traverse the left subtree: D B E
2. Visit the root: A
3. Traverse the right subtree: C F
 Inorder Traversal: D B E A C F
Postorder Traversal (Left, Right, Root)
1. Traverse the left subtree: D E B
2. Traverse the right subtree: F C
3. Visit the root: A
 Postorder Traversal: D E B F C A
Preorder Traversal (Root, Left, Right)
1. Visit the root: A
2. Traverse the left subtree: B D E
3. Traverse the right subtree: C F
 Preorder Traversal: A B D E C F

Q.35 Discuss the following terms associated with a tree (CO-5) 1. Path 2. Level 3. Degree of a Node
4. Terminal Node 5. Root Node
Sure, let's discuss these terms associated with a tree:
1. Path
A path in a tree is a sequence of nodes and edges connecting a node with a descendant. The path
length is the number of edges in the path. For example, in the tree below, the path from node A to
node E is A -> B -> E.
2. Level
The level of a node in a tree is the number of edges on the path from the root node to the node. The
root node is at level 0, its children are at level 1, and so on.
3. Degree of a Node
The degree of a node is the number of children it has. For example, in the tree below, node A has a
degree of 2 (children B and C), node B has a degree of 2 (children D and E), and node C has a degree
of 1 (child F).
4. Terminal Node
A terminal node (also known as a leaf node) is a node that does not have any children. It is the end
point of a path. For example, in the tree below, nodes D, E, and F are terminal nodes.
5. Root Node
The root node is the topmost node of a tree. It is the only node in the tree that does not have a
parent. All other nodes are descendants of the root node.
Example Tree:
A
/\
B C
/\ \
D E F
Q.36 List Various Searching Techniques. Compare them and write algorithm of anyone.
Various Searching Techniques
1. Linear Search (Sequential Search):
o Description: Checks each element in the list one by one until the desired element is
found or the list ends.
o Time Complexity: O(n)
o Best Used For: Small or unsorted lists.
2. Binary Search:
o Description: Divides the sorted list into halves to find the desired element. It
repeatedly compares the target value to the middle element of the list.
o Time Complexity: O(log n)
o Best Used For: Large, sorted lists.
3. Jump Search:
o Description: Divides the list into blocks of fixed size and performs a linear search
within the block where the target element may be.
o Time Complexity: O(√n)
o Best Used For: Sorted lists.
4. Interpolation Search:
o Description: An improved variant of binary search that works on the principle of
probing the position of the required value.
o Time Complexity: O(log log n) (average case)
o Best Used For: Uniformly distributed sorted lists.
5. Exponential Search:
o Description: Finds the range where the target element may be and then performs a
binary search within that range.
o Time Complexity: O(log n)
o Best Used For: Large, sorted lists.
Algorithm:
1. Start with the left and right pointers at the beginning and end of the list, respectively.
2. Calculate the middle index.
3. Compare the target value with the middle element.
4. If the target value is equal to the middle element, return the index.
5. If the target value is less than the middle element, move the right pointer to the middle
index - 1.
6. If the target value is greater than the middle element, move the left pointer to the middle
index + 1.
7. Repeat steps 2-6 until the target value is found or the left pointer exceeds the right pointer.
8. If the target value is not found, return -1.
Q.35 Why Stack is known as LIFO? What is the significance of TOPpointer?
Why Stack is Known as LIFO?
A stack is known as a Last In, First Out (LIFO) data structure because the last element added to the
stack is the first one to be removed. This is similar to a stack of plates where you can only add or
remove the top plate. The LIFO principle ensures that the most recently added element is always the
one that is removed first.
Significance of TOP Pointer
The TOP pointer is crucial in the implementation of a stack. It keeps track of the index of the top
element in the stack. Here are its main functions:
1. Insertion (Push Operation): When a new element is added to the stack, the TOP pointer is
incremented, and the new element is placed at the position indicated by the TOP pointer.
2. Deletion (Pop Operation): When an element is removed from the stack, the element at the
position indicated by the TOP pointer is removed, and the TOP pointer is decremented.
3. Access: The TOP pointer allows direct access to the top element of the stack, enabling
efficient push and pop operations.
Example:
c
#include <stdio.h>
#define MAX 10

int stack[MAX];
int top = -1;

void push(int value) {


if (top == MAX - 1) {
printf("Stack Overflow\n");
} else {
top++;
stack[top] = value;
}
}

int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
} else {
int value = stack[top];
top--;
return value;
}
}

int main() {
push(10);
push(20);
printf("Popped value: %d\n", pop());
return 0;
}
In this example, the top pointer is used to manage the stack operations efficiently, ensuring that the
stack follows the LIFO principle.
Q.27 Write the difference between Static and Dynamic Memory allocation.
Difference Between Static and Dynamic Memory Allocation
Static Memory Allocation:
1. Definition: Memory is allocated at compile time before the program runs.
2. Size: The size of the memory block is fixed and cannot be changed during runtime.
3. Lifetime: The memory is allocated for the entire duration of the program.
4. Efficiency: Faster allocation and deallocation since it is done at compile time.
5. Example: Declaring an array with a fixed size.
c
int arr[10]; // Static memory allocation
Dynamic Memory Allocation:
1. Definition: Memory is allocated at runtime as needed.
2. Size: The size of the memory block can be changed during runtime.
3. Lifetime: The memory is allocated and deallocated as needed during the program's
execution.
4. Efficiency: Slower allocation and deallocation since it is done at runtime.
5. Example: Using functions like malloc(), calloc(), realloc(), and free() in C.
c
int *arr = (int*)malloc(10 * sizeof(int)); // Dynamic memory allocation

You might also like