Data Structure - Solution
Data Structure - Solution
B TECH
(SEM-III) THEORY EXAMINATION 2020-21
BASIC DATA STRUCTURE AND
ALGORITHM
Time: 3 Hours Total Marks: 100
Note: 1. Attempt all Sections. If require any missing data; then choose suitably.
SECTION A
Ans:“Big O notation is a mathematical notation that describes the limiting behavior of a function
when the argument tends towards a particular value or infinity. Definition: A theoretical
measure of the execution of an algorithm, usually the time or memory needed, given the problem
size n, which is usually the number of items. Informally, saying some equation f(n) = O(g(n))
means it is less than some constant multiple of g(n). The notation is read, "f of n is big oh of g of
n".
Formal Definition: f(n) = O(g(n)) means there are positive constants c and k, such that 0 ≤ f(n)
≤ cg(n) for all n ≥ k. The values of c and k must be fixed for the function f and must not depend
on n.
SECTION B
Attempt any three of the following:
Qa: What is meant by string operation? Discuss with the help of any example.
Ans: Strings are defined as an array of characters. The difference between a character array and a
string is the string is terminated with a special character ‘\0’.
Declaring a string is as simple as declaring a one dimensional array. Below is the basic syntax for
declaring a string in C programming language.
char str_name[size];
Operation Description
Concatenati
The Addition operator, “+”, can be used to concatenate strings together.
on
Formatting The STRING function is used to format data into a string. The READS procedure
Data can be used to read values from a string into IDL variables.
The ToLower() method returns a copy of the string converted to lowercase.
Case Similarly, the ToUpper() method returns a copy converted to uppercase.
Folding The CapWords() method returns a copy where the first letter of each word is
capitalized. See also the STRLOWCASE and STRUPCASE functions.
White Space The Compress() and Trim() methods can be used to eliminate unwanted white
Removal space. See also the STRCOMPRESS and STRTRIM functions.
Length The Strlen() method (or STRLEN function) returns the length of the string.
See
the CharAt(), Extract(), IndexOf(), Insert(), LastIndexOf(), Remove(), Replace(),
Substrings
Reverse(), and Substring() methods. See also the STRPOS, STRPUT,
and STRMID routines.
Splitting and The Split() method is used to break strings apart, and the Join() method can be
Joining used to join them. See also the STRSPLIT and STRJOIN functions.
The "EQ" operator can be used to directly compare two strings.
Comparing The Contains(), EndsWith(), Matches(), and StartsWith() methods can be used to
Strings compare portions of strings. See also the STRCMP, STRMATCH,
and STREGEX functions.
Qb: Explain Priority Queue and Define Big-Oh notation and find the complexity of the
following recursive function T(n) = 4T(n/2)+nlog n
Ans:
Priority Queue: A priority queue is a special type of queue in which each element is associated
with a priority value. And, elements are served on the basis of their priority. That is, higher
priority elements are served first.
However, if elements with the same priority occur, they are served according to their order in the
queue.
O Notation:
F(n)=O(g(n)) :
positive constants c and n0, such that n n0,
T(n)=4T(n/2)+n∗log(n)T(n)=4T(n/2)+n∗log(n)
T(n/2)=4T(n/4)+(n/2)∗(log(n)−1)T(n/2)=4T(n/4)+(n/2)∗(log(n)−1)
Plugging in 1st Eqn. :
T(n)=(42)T(n/4)+(4∗(n/2)(log(n)−1))+n∗log(n)T(n)=(42)T(n/4)+(4∗(n/2)(log(n)−1))+n∗log(n)
Also,T(n/4)=4T(n/8)+(n/4)∗(log(n)−2)Also,T(n/4)=4T(n/8)+(n/4)∗(log(n)−2)
Plugging again…
T(n)=(43)T(n/8)+(4∗(n/4)(log(n)−2))+(4∗(n/2)(log(n)−1))+n∗log(n)
T(n)=(4k)T(n/2k)+4∗(∑2k((n/2r−1)(log(n)−(r−1)))+n∗log(n)T(n)=(4k)T(n/2k)+4∗(∑2k((n/2r−1)(log(n)−(r−1)))+n∗log(
n)
k
Now , set n=2 .
Qc: Discuss Complete Binary Trees. Draw a binary tree for following data:
{15 22 12 1 8 7 17 25 23 6 9 2}
Ans:
• A complete binary tree is a binary tree in which every level, except possibly the last, is
completely
• In complete binary tree all the nodes must have exactly two children and at every level of
complete binary tree there must be 2 level number of nodes.
• For example at level 2 there must be 2^2 = 4 nodes and at level 3 there must be 2^3 = 8
nodes.
• A complete binary tree of depth d is called strictly binary tree if all of whose leaves are at
level d.
• A complete binary tree has 2d nodes at every depth d and 2d -1
Ans: Breadth-first search (BFS) is an algorithm that is used to graph data or searching tree or
traversing structures. The full form of BFS is the Breadth-first search.
The algorithm efficiently visits and marks all the key nodes in a graph in an accurate breadthwise
fashion. This algorithm selects a single node (initial or source point) in a graph and then visits all
the nodes adjacent to the selected node. Remember, BFS accesses these nodes one by one.
Once the algorithm visits and marks the starting node, then it moves towards the nearest
unvisited nodes and analyses them. Once visited, all nodes are marked. These iterations continue
until all the nodes of the graph have been successfully visited and marked.
Graph traversal requires the algorithm to visit, check, and/or update every single un-visited node
in a tree-like structure. Graph traversals are categorized by the order in which they visit the
nodes on the graph.
BFS algorithm starts the operation from the first or starting node in a graph and traverses it
thoroughly. Once it successfully traverses the initial node, then the next non-traversed vertex in
the graph is visited and marked.
Hence, you can say that all the nodes adjacent to the current vertex are visited and traversed in
the first iteration. A simple queue methodology is utilized to implement the working of a BFS
algorithm, and it consists of the following steps:
Step 1)
Each vertex or node in the graph is known. For instance, you can mark the node as V.
Step 2)
In case the vertex V is not accessed then add the vertex V into the BFS Queue
Step 3)
Start the BFS search, and after completion, Mark vertex V as visited.
Step 4)
The BFS queue is still not empty, hence remove the vertex V of the graph from the queue.
Step 5)
Retrieve all the remaining vertices on the graph that are adjacent to the vertex V
Step 6)
For each adjacent vertex let's say V1, in case it is not visited yet then add V1 to the BFS queue
Step 7)
BFS will visit V1 and mark it as visited and delete it from the queue.
Step 1)
You have a graph of seven numbers ranging from 0 – 6.
Step 2)
0 or zero has been marked as a root node.
Step 3)
Step 4)
Remaining 0 adjacent and unvisited nodes are visited, marked, and inserted into the queue.
Step 5)
Traversing iterations are repeated until all nodes are visited.
Qe: Explain quick sort. Draw a tree of the following with the help of Quick sort:
{52,37,63,14,17,8,6,25}
Quick Sort is one of the different Sorting Technique which is based on the concept of Divide
and Conquer, just like merge sort. But in quick sort all the heavy lifting(major work) is done
while dividing the array into subarrays, while in case of merge sort, all the real work happens
during merging the subarrays. In case of quick sort, the combine step does absolutely nothing.
It is also called partition-exchange sort. This algorithm divides the list into three main parts:
For example: In the array {52, 37, 63, 14, 17, 8, 6, 25}, we take 25 as pivot. So after the first
pass, the list will be changed like this.
{6 8 17 14 25 63 37 52}
Hence after the first pass, pivot will be set at its position, with all the elements smaller to it on its
left and all the elements larger than to its right. Now 6 8 17 14 and 63 37 52 are considered as
two separate sunarrays, and same recursive logic will be applied on them, and we will keep
doing this until the complete array is sorted.
SECTION C
Q3 a: What do you understand by complexity of an algorithm? Discuss at least 4 types of
string operations in details.
Ans: Space required to complete the task of that algorithm (Space Complexity).
Time required to complete the task of that algorithm (Time Complexity)
Space Complexity:
When we design an algorithm to solve a problem, it needs some computer memory to complete
its execution. For any algorithm, memory is required for the following purposes...
1. To store program instructions.
2. To store constant values.
3. To store variable values.
4. And for few other things like function calls, jumping statements etc,.
Total amount of computer memory required by an algorithm to complete its execution is
called as space complexity of that algorithm
Time Complexity:
• Every algorithm requires some amount of computer time to execute its instruction to
perform the task. This computer time required is called time complexity.
The time complexity of an algorithm can be defined as follows...
The time complexity of an algorithm is the total amount of time required by an algorithm
to complete its execution.
Operation Description
Concatenati
The Addition operator, “+”, can be used to concatenate strings together.
on
Formatting The STRING function is used to format data into a string. The READS procedure
Data can be used to read values from a string into IDL variables.
The ToLower() method returns a copy of the string converted to lowercase.
Case Similarly, the ToUpper() method returns a copy converted to uppercase.
Folding The CapWords() method returns a copy where the first letter of each word is
capitalized. See also the STRLOWCASE and STRUPCASE functions.
White Space The Compress() and Trim() methods can be used to eliminate unwanted white
Removal space. See also the STRCOMPRESS and STRTRIM functions.
Length The Strlen() method (or STRLEN function) returns the length of the string.
See
the CharAt(), Extract(), IndexOf(), Insert(), LastIndexOf(), Remove(), Replace(),
Substrings
Reverse(), and Substring() methods. See also the STRPOS, STRPUT,
and STRMID routines.
Splitting and The Split() method is used to break strings apart, and the Join() method can be
Joining used to join them. See also the STRSPLIT and STRJOIN functions.
The "EQ" operator can be used to directly compare two strings.
Comparing The Contains(), EndsWith(), Matches(), and StartsWith() methods can be used to
Strings compare portions of strings. See also the STRCMP, STRMATCH,
and STREGEX functions.
Q3b: What is the use of sparse matrix? Explain how sparse matrix is different from
normal Matrix? Discuss.
For example, consider a matrix of size 5 X 6 containing 6 number of non-zero values. This
matrix can be represented as shown in the image...
In above example matrix, there are only 6 non-zero elements ( those are 9, 8, 4, 2, 5 & 2) and
matrix size is 5 X 6. We represent this matrix as shown in the above image. Here the first row in
the right side table is filled with values 5, 6 & 6 which indicates that it is a sparse matrix with 5
rows, 6 columns & 6 non-zero values. The second row is filled with 0, 4, & 9 which indicates the
non-zero value 9 is at the 0th-row 4th column in the Sparse matrix. In the same way, the
remaining non-zero values also follow a similar pattern.
Q4a: What do you understand by D Queue? Discuss D -Queue with the help of
suitable example.
Ans:
A Deque or deck is a double-ended queue.
It is also known as “Head-Tail Linked List”
Allows elements to be added or removed on either the ends.
Dequeue can be implemented using Circular Array or a Circular doubly linked list where
Dequeue[n-1] is followed by Dequeue[0]
void insert_left()
{
int added_item;
printf("Input the element for adding in queue : ");
scanf("%d", &added_item);
if ((right+1)%MAX==left)
{ printf("The queue is Full\n");
}
else if(left==-1 && right==-1)
{ printf("The queue is Empty\n");
left=right=0;
deque_arr[left]=added_item;
}
else if(left== 0)
{ left=MAX-1;
deque_arr[left] = added_item ;
}
else
{
left=left-1;
deque_arr[left] = added_item ;
}}
Q 4 b: What do you understand by PUSH and POP Operation? Discuss the tower of Hanoiproblem in
detail.
Ans. PUSH operation:
In a stack, push() is a function used to insert an element into the stack. In a stack, the new element is always
inserted at top position. Push function takes one integer value as parameter and inserts that value into the stack.
We can use the following steps to push an element on to the stack...
Step 1 - Check whether stack is FULL. (top == SIZE-1)
Step 2 - If it is FULL, then display "Stack is FULL!!! Insertion is not possible!!!" and terminate the function.
Step 3 - If it is NOT FULL, then increment top value by one (top++) and set stack[top] to value (stack[top] =
value).
POP Operation:
pop() - Delete a value from the Stack using array
In a stack, pop() is a function used to delete an element from the stack. In a stack, the element is always deleted
from top position. Pop function does not take any value as parameter. We can use the following steps to pop an
element from the stack...
Step 1 - Check whether stack is EMPTY. (top == -1)
Step 2 - If it is EMPTY, then display "Stack is EMPTY!!! Deletion is not possible!!!" and terminate the
function.
Step 3 - If it is NOT EMPTY, then delete stack[top] and decrement top value by one (top--).
TOH Problem:
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. 1. one disk at a
time. 2 top of the disk can be poped 3. no big disk on top of smaller disk
Step 1 − Move n-1 disks from source to aux
Step 2 − Move nth disk from source to dest
Step 3 − Move n-1 disks from aux to dest
The objective of the puzzle is to move the entire stack to another rod, obeying the following
simple rules:
1) Only one disk can be moved at a time.
2) Each move consists of taking the upper disk from one of the stacks and placing it on top of
another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
3) No disk may be placed on top of a smaller disk.
Q 5 a: Sort the following data with the help of Heap sorting and write the Pseudo Code for
the above: {23,10,16,11,20}
Heap Sort Algorithm:
void heapify(int arr[], int n, int i)
{ int largest = i;
int l = 2*i + 1;
int r = 2*i + 2;
// if left child is larger than largest so far
if (l < n && arr[l] > arr[largest])
largest = l;
// if right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// if largest is not root
if (largest != i)
{
swap(arr[i], arr[largest]);
// recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
void heapSort(int arr[], int n)
{
// build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// one by one extract an element from heap
for (int i=n-1; i>=0; i--)
{ // move current root to end
swap(arr[0], arr[i]);
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
Q5b: Explain Extended binary tree. Discuss the Type of Binary tree in detail.
Ans: Types of binary tree:
• Complete binary tree
• Strictly binary tree
• Almost complete binary tree
• Extended Binary Tree
Q 6 a: Discuss the Kruskal Algorithm with the help of an example.
Ans:
Total cost of tree= 7+3+3+2+2
= 17 (minimum)
Q 6 b: What is minimum cost spanning tree with respect to data structure? Explain with
example.
Ans:
Shortest path algorithms
There are two algorithms which are being used for this purpose.
o Prim's Algorithm
o Kruskal's Algorithm
Q7a: What do you understand by B-Tree? Differentiate between B-Tree & B+ Tree.
Ans:
B-Tree:
B-Tree is known as a self-balancing tree as its nodes are sorted in the inorder traversal. In B-tree, a node can have more
than two children. B-tree has a height of logM N (Where ‘M’ is the order of tree and N is the number of nodes). And the
height is adjusted automatically at each update. In the B-tree data is sorted in a specific order, with the lowest value on
the left and the highest value on the right. To insert the data or key in B-tree is more complicated than a binary tree.
There are some conditions that must be hold by the B-Tree:
All the leaf nodes of the B-tree must be at the same level.
Above the leaf nodes of the B-tree, there should be no empty sub-trees.
B- tree’s height should lie as low as possible.
B+ Tree
B+ tree eliminates the drawback B-tree used for indexing by storing data pointers only at the leaf nodes of the tree. Thus,
the structure of leaf nodes of a B+ tree is quite different from the structure of internal nodes of the B tree. It may be noted
here that, since data pointers are present only at the leaf nodes, the leaf nodes must necessarily store all the key values
along with their corresponding data pointers to the disk file block, in order to access them. Moreover, the leaf nodes are
linked to providing ordered access to the records. The leaf nodes, therefore form the first level of the index, with the
internal nodes forming the other levels of a multilevel index. Some of the key values of the leaf nodes also appear in the
internal nodes, to simply act as a medium to control the searching of a record.
Let’s see the difference between B-tree and B+ tree:
S.
NO B tree B+ tree
All internal and leaf nodes Only leaf nodes have data
1. have data pointers pointers
Since all keys are not All keys are at leaf nodes,
available at leaf, search often hence search is faster and
2. takes more time. accurate..
Insertion takes more time and Insertion is easier and the results are
4. it is not predictable sometimes. always the same.
// Driver code
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int n = sizeof(arr) / sizeof(arr[0]);
// Function call
int result = search(arr, n, x);
(result == -1)
? printf("Element is not present in array")
: printf("Element is present at index %d", result);
return 0;
}
Bubble Sort:
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in
wrong order.
Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass
without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) –> ( 124 58)
( 1 2 4 5 8 ) –> ( 124 58)
( 1 2 4 5 8 ) –> ( 124 58)
( 1 2 4 5 8 ) –> ( 124 58)