Data Structures & Algorithms ERE 3rd Sem
Data Structures & Algorithms ERE 3rd Sem
ALGORITHM
Introduction
Stacks & Queues 13
Linked List
32
Trees 46
Graphs
88
Sorting & Hashing
106
Miscellaneous 143
NOTE:
MAKAUT course structure and syllabus of 3 semester has been changed from 2019
Subject organization of Data Structure and Algorithm has been
changed slightly.
Few new topics have been introduced. Taking special care of
this matter we are
providing the relevant MAKAUT university solutions of Data Structure
and Algorithm
CS, IT) and some model questions and answers of newly introduced topics
so that
Students will get an idea about university questions patterns
POPULAR PUBLICATIONS
INTRODUCTION
Chapter at a Glance
Data (plural of "datum"), refers to qualitative or quantitative attributes of a variable or set of
variables. Typically, data are the results of measurements and can be the basis of graphs,
images or observations of a set of variables.
Metadata is a data, containing a description of other data. Earlier term for metadata is
ancillary data.
Data structure: Data may be organized in many different ways. The logical or mathematical
model of a particular organization of data is called data structure
Classification: Data structure can be classified as linear and non-linear.
Linear data structure: The data structure is said to be linear, if its element forms a sequence
or linear list. Linear data structures organize their data elements in a linear fashion.
Non-linear data structure: In nonlinear data strüctures, data clements are not organized in a
sequential fashion. A data item in a nonlinear data structure could be attached to several other
data elements to reflect a special relationship among them and all the data items cannot be
traversed in a single run.
Various operations can be performed on data structure. List of some frequently used
operations are given below:
1. Traversing: sometimes also called as visiting, means accessing the required record so as to
process the data.
2. Searching: finding the location of record to be processed.
3. Inserting: adding a new record to the structure
4. Deleting: removing the record from the structure.
5. Sorting: arranging the record in some logical order.
6. Merging: combining two different sets of records to form a final set of records.
Abstract data type (ADT): Abstract Data Types are a set of data values and associated
operations that are precisely independent of any particular implementation. The term abstract
signifies that the data type will only set the rule of it's usage but how it will be used depends
on the implementation. For example stacks and queues are called abstract data types. The
stack data type defines two abstract methods PUSH and POP.
are
The basic properties of an algorithm
Input: Each algorithm is supplied with a zero or more external quantities.
Output: Each algorithm must produce atleast one quantity.
Definiteness: Each instruction must be clear and unambiguous.
Finiteness: The algorithm must terminate after a finite number of steps within finite time.
Efectiveness: Each instruction must be šufficiently basic and also be feasible.
Analysis of an algorithm means, to determine the amount of resources (such as time au
storage) necessary to execute it. Most algorithms are designed to work with inputs of arbitra
length. Usually the efficiency or running time of an algorithm is stated as a function retas
the input length to the number of steps (time complexity) or storage locations (pa
complexity).
the
In theoretical analysis of algorithms it is common to estimate their complexity in
csymptotic sense, i.e., to estimate the complexity function for arbitrarily large input. BE
DSA-2
DATA STRUCTURE & ALGORITHM
notation, omega notation and theta notation are used for this Usually asymptotic estimates
are used because ditferent implementations of the same algorithm may differ in eficieney.
However the cficiencies of any two "reasonable" implementations of a given algorithrm are
related by a constant multiplicative factor called a hidden constant.
Complexity: There are two types of complexities of an algorithm, time complexity and space
complexity
The time complexity of an algorithm is the amount of time the computer requires to execut
the algorithm.
The space complevity of an algorithm is the amount memory
space the computer requires,
of
completing the execution of the algorithm.
3. Which of the following is the best time for an algorithm? WBUT 20101
a) o(n) b) olog,) o(2")
er) d) O(nlog, n)
Amswer: (b)
4.Four algo.s do the same task. Which algo. should execute the slowest for large
values ofn? WBUT 2010]
a) o) b) O(n) o) O(log, n) d) o(2")
Answer: (d)
6. Which of the following algorithm should execute the slowest for large values of
N? WBUT 2012]
a) O (N) b) O (N) c)Olog:N) d) None of these
Answer: (b)
8. A dynamic data structure where we can search for desired records inO(logn)
time is WBUT 2013
a) heap b) binary search tree
c) circularty linked list d) array
Answer: (b)
9. For Column Major, what is the address of [3, 2] th element of a 3x4 Matrix
(contains integer number)? It is given that the 'Base Address is 2000'. [WBUT 2013]
2010
a) b) 2012 c) 2016 d) 2018
Answer: should be 2020
10. Which of the following expressions access the (i, j)th entry of a (m x n) matrix
stored in column major order? WBUT 2015]
a)nx(i-1)+j b) m x -1)+ i
DSA-4
DATA STRUCTURE & ALGORITHM4
2d Part:
A matrix is represented in memory as 2D array, like A [i, i], where a
i is a row and j iS
column.
If there are m rows and n columns, then total elements in a matrix or size of a matrix is m
xn elements. This m xn elements requires m x n units of storage.
A matrix, that is tilled with mostly zeroes
(more than 2/3 elements are zero), is called as a
sparse matrix.
Now, if there is a sparse matrix of order mx n, and if we use a 2D array of order m *n to
store this matrix, then there is basically wastage of large amount of memory.
Now, a sparse matrix can be stored as a list of three tuples of the form (i, j, value).
In this way we can store only non-zero elements.
0 0 0 01 0
2 0 0 0 0 0
0-3 0 00 0
0 0 0 70 0
0 0 0 0 0 30
Let us consider a matrix M(5x6)
Here the number of non-zero elements t= 5.
The array A [0..., 1...3] can store all the non zero elements as given below:
A[O]
A[1] The element A [0, 1] and A [0, 2] contain the number of
A[2] 2 2 rows and columns of the matrix. A[0, 3] contains total
A[3] 3 -3 number of non-zero items.
A4] 4
A[S) 5 30
2. Show that the function f(n) defined by: WBUT 2007, 2010, 2016, 2018]
S)=1
S)=fa-)+ for n>1
DSA-5
POPULAR PUBLICATIONs
Answer:
1" Part:
f(n) f(n-1)+1/n
f(n-2)+1/(n-1)+1/n
f(n-3)+1/n-2)+1/(n-1)+1/n
'***'*****'************************* *****
***********************************
f(2-1)+1/2+1/3...+1/(n-1)+1/n
1/1+ 1/2 +1/3 +...... 1/n t
These types of numbers are called Harmonic numbers.
We can evaluate this type of series just by integrating 1/x from % to n + %.
After integrating, we get the result as In(n + A)- In
In n-0.7
Hence, we can write the complexity as O(log n).
Big O notation:
The Big Oh (the "O" stands for "order of") notation is used tó classify functions by their
asymptotic growth function and hence finding the time complexity of an algorithm.
There are two types of complexities of an algorithm, time, complexity and space
complexity. The time complexity of an algorithm is the amount of time the computer
requires to execute the algorithm. The space complexity of an algorithm is the amount of
memory the computer needs to run to complete the execution of the algorithm. The
algorithms are compared based on their performances. The performance is measured in
terms of time complexity & space complexity. Based on the nature of the input, time
complexity can be of three different types: best case, average case and worst case.
The different computing functions are measured as:
n, ", n', logn, nlog2n, 2".
The rate of growth of all these functions is shown below:
H
n log
2"
-log nn
2
Let fn) and gin) be functions, where n is a positive integer. We write fn) = Q(g»)) i
and only ifgtn) = Ofin).
DSA-6
ALGORITHM
DATA STRUCTURE &
8:
Letfn) and gtn) be functions, where n is a positive integer. We write fn) = 6(g) it
and only if gtn) = Ofn). and gtn) = an).
3.Derive values related to the average case and worst case behaviour of 5ubbe
Sort algorithm. Also, confirm that the best case behavior is O(n). [WBUT 2007
OR,
Write an algorithm for sorting a list numbers in ascending order using bubble sort
technique and find its time complexity. WBUT 2017]
Answer:
The algorithm for bubble sort is given as follows:
Procedure: BubbleSort (List [])
Inputs: List[] - A list of numbers
Locals: i, j -
integers
Begin:
For i = 0 to List.size-1
For j itl to List.Size-1
If List[il > List[jl, Then
Swap List [il and List[i]
End If
Next j
Next i
Analysis:
The size of the sorting problem is related to the : N of the list As N increases, we
expect the execution time to increase as well.
The innermost instruction is to swap two list elements. Regardless of how long the list is,
this always takes the same amount of time, and so the swap instruction is O(1) with
respect to N. Surrounding that instruction is an if statement, which either executes its
body, or does not; in the worst case, it will execute its body. Again, the if statement is
(1).
The if statement is executed as many times as the inner loop iterates, and the inner loop
executes as many times as the outer loop iterates. During the first iteration (i = 0), the
innerloop executes N-1 times, during the second iteration (i = 1), N-2 times, and so
on.
o NN--1)
number-of-loops time-per-loop
)-o(- .
So the complexity is O(N2) in the average case as well worst case.
The best case would be if the list were already sorted.
There will be comparisons as it is but no exchanges and execution time is in O(N2).
But we keep a track of exchanges in each pass and teminate the program checking
if if
no there are then the program would require only one pass (N-1)
no exchanges, and max.
Comparisons are required in that single pass ana we can say that the complexity is
order of ON).
of
DSA-7
POPULAR PUBLICATIONS
9. Do a comparison among
Data Type, Abstract Data Type
and Data structure
Answer: WBUT 2013]
Data type consists of the values
it represents and the operations defined
or character data types are found upon it. Integer
in nearly all computers, and they have
operations that can be done with well-detined
them. For example, the integer data type has
for addition, subtraction, multiplication, operations
perform these arithmetic operations and division. The computer knows how to
with any two integers because these operations are
part of the integer data type.
A data type can be considered
and its implementation is hidden
abstract when it is defined in terms of operations on it,
(so that we can always replace one implementation
another for, e.g., efficiency reasons, and this will with
not interfere with anything in the
program). Thus, speaking about such a type, we
leave its implementation aside
considering it irrelevant to the topic, unless we directly
discuss the implementation.
A data structure is an arrangement of
data in a computer's memory or even disk storage.
An example of several common data
structures are arrays, linked lists, queues, stacks,
binary.trees, and hash tables. Data Structure is an implementation of ADT. Many
ADT
can be implemented as the same Data Structure.
10. What are the differences between linear and non-linear data structures?
WBUT 2013, 2014]1
OR
Explain linear and non-linear data structure with example. WBUT 2019]
Answer:
Data structure can be classified as linear and non-linear.
Linear data structure: The data structure is said to be linear, if its element forms a
sequence or linear list. There are two basic ways of representing such structure in
memory. Here the elements are traversed sequentially starting from the beginning.
(1) Linear relationship between data elements is represented by means of sequential
memory locations. Ex: Arrays.
(2) Linear relationship between data elements is represented by means of pointers and
links. Ex: Linked list.
Non-linear data structure: They are used to represent the data having a hierarchical
relationship between elements. Here the elements are not traversed sequentially, rather
they are traversed in a non linear fashion. For example, in case of the tree, we have to
start from the root but we have to traverse either left subtree or right subtree, but not the
both.
Ex: Graphs and Trees.
DSA-9
POPULAR PUBLICATIONS
12. a) Suppose one 2-D array is initialized as int a 15]|171; Base address is 4000. Find
the location of element a [2]14] in row major form and column major fomm
b) Define Sparse Matrix. WBUT 2014
Answer:
a) Assume that the size of each element is 4 bytes.
In row major order the address will be
Loc (A(ij)) = Lo + ((i-1)* n+G-1) *c
Therefore,
Loc (A(2,4)) = 4000+ (2-1)* 7+ (4-1))* 4=4000+ (7+3)* 4
= 4000 + 40= 4040
14. IH
7(m)=a, +a,x+a,x +a,+.+a,, then prove T(m)= ®(*). wBUT 2017
Answer:
To prove that fn) =(g(n)) we have to find cl, c2>0 and no
DSA-10
DATA SIRUCTURE & ALGORITHM
where
Examples:
1. If student 's grade is greater than or equal to 80
Print "passed"
else
Print "
failed"
2. Set total to zero
Set grade counter to one
While grade counter is lesS than or equal to ten
Input the next grade
Add the grade into the total
ec the class average to the total divided by ten
Print the class average.
. Initialize total to zero
nitialize
nput the
counter to zero
first grade
Wlle the user has not as yet entered the sentinel
aad this grade into thé running total
aad one
to the grade counteer
DSA-11
POPULAR PUBLICATIONS
DSA-12
ALGORITHM
DATA STRUCTURE &
Chapter at a Glance
Stacks: A stack is an abstract data type, which declares two methods PUSH and POP. Stacks
are implemented either by an array or by a linked list.
The PUSH operation allows us to insert data at the end of an array or linked list.
The POP operation allows us to remove data from the end of an array or linked list.
A STACK is called a last in first out (LIFO) system.
A stack may be represented by a linked list. The first node of the list will
be the topmost
is called
element of the stack and is pointed by a top pointer. This type of stack representation
linked stack. The stack can be declared as follows:
typedef struct linked_list
int data;
struct linked_1ist *next;
) lstack;
lstack *top;
Various types of expression: A mathematical expression involves constants (operands) and
operations (operators).
Infix notation; operandl operator operand2, A+B
Prefix notation: operator operandI operand2, + A B
Postfix notation: operand 1 operand2 operator, A B+
Conversion from INFIX to POSTFIX expression: In order to convert the infix to its
corresponding postfixes form; we need to do the following steps:
Fully parenthesize the expression according to the priority of different operators.
Move all operators so that they replace their corresponding right parentheses.
>Delete all parentheses.
The priorities of different operators are given below:
Operators PriorityY
Unary-,unary t, not ()
,,%, and (/&&c)
,or (/)_ 2
1
Priority Queue: priority queue is essentially a list of items in which each item has.
associated with it a priority. In general, different items may have different priorities and we
speak of one item having a higher priority than another. Given such a list we can determine
which is the highest (or the lowest) priority item in the list. Items are inserted into a priórity
queue in any, arbitrary order. However, items are withdrawn.from a priority queue in order of
their priorities starting with the highest priority tem first. Two elements with the same
priority are processed according to the order in which they were added to the queue.
De-queue: De-queue is a linear data structure, where insertions and deletions are made to or
from either end of the structure.
DSA-13
POPULARPUBLICATIONS
2. The prefix expression for the infix expression a* (b + c)le-fis WBUT 2008]
a) 'a+ bc-ef b)-+abcef c)-ra+ bcef d) None of these
Answer: (a)
7. The operation for adding an entry to a stack is traditionally called WBUT 2013]
a) Add b) Append c) Insert d) Push
Answer: (d)
9. The heap (represente by an array) constructed from the list of numbers 30, 10,
80, 60, 15, 55, 17 is
a) 60, 80, 55, 30, 10, 17, 15
WBUT 2014]
b) 80, 55, 60, 15, 10, 30, 17
c) 80, 60, 30, 17, 55, 15, 10 d) none of these
Answer: (b)
10. The postfix equivalent of the prefix*+ab-cd is WBUT 2014, 2015, 2016, 2019]
a) ab + cd-* b) abcd +-* c) ab +cd*- d) ab+-cd*
Answer: (a)
DSA-14
DATA STRUCTURE & ALGORITHM
11. The following sequence of operations is performed on a stack: push (1), push
(2), pop. push (1), push (2), pop, pop, pop, push (2), pop. The sequence of popped
out values are WBUT 2014, 2019]
a) 2, 2, 1, 1, 2 b) 2,2,1,2, 2 c) 2, 1, 2, 2,1 d) 2, 1,2, 2, 2
Answer: (a)
15. Insertingan item into the stack when stack is not full is called .. ..
.
operation and deletion of item from the stack, when stack is not empty is called
Operation. [WBUT 2017]
a) push, pop b) pop, push
c) insert, delete d) delete, insert
Answer: (a)
16. To make a queue empty, elements can be deleted till WBUT 2018]
a) front = rear +1 b) front = rear- 1
c) front = rear d) None of these
Answer: (a)
17. Which among the following are applications of queues? WBUT 2019]
a) Queues keep track of events waiting to be handled, like multiple button
clicks
b) Queues are used for evaluation of arithmetic expressions
c) Queues are used in parsing
d) None of these
Answer: (a)
DSA-15
POPULAR PUBLICATIONS
AB
AB+
AB+
AB+C
AB+C*
AB+C*
AB+CD
ABHC D
AB+C DE
AB+CDE
AB+C'DE
ABC"DE
AB+C*DE-F
AB+C"DE-F
AB+C DE-FG
AB+C DE-FG+
NONE EMPTY AB+C*DE-FG+/-
b) A heap is a tree-based data structure that satisfies the heap property: if B is a child
node of A, then key(A) 2 key(B). This implies that an element with the greatest key is
always in the root node, and so such a heap is sometimes called a max-heap.
DSA-16
ALGORITHM
DATA STRUCTURE
&
D AB
AB*
ABC
AB
C
AB'C
+ ABCD
AB'CD
AB CDE
ABCDE
AB'CDE
ABCDEF
+ AB'CDEF.
G AB'CDE-"FG
NONE NONE ABCDE*FG*+
DSA-17
POPULAR PUBLICATIONS
S. a)Consider the array int a [10] (10] and the base address 2000, then calculate the
address of the array a [2] [3] in the row and column major ordering. WBUT 2012]
Answer:
In now major ordering the linear offset from the beginning of the array to any given
element A{row][column) can then be computed as:
offiset = row*NUMCOLS + column
Thus a[213] will have address 2000+2*10+3 2023
In column major ordering the memory offset could then be computed as:
offset row +column*NUMROWS
Thus a[2]B] will have address = 2000+2+3*10 2032
DSA-18
DATASTRUCTURE & ALGORITHM
Stack can be considered as
a priority queue where
inserted are considered higher the priorities of each element being
than the previous one. This will let it behave e
structure (1.e., stack). like a Liro
8. Suppose a queue is
implemented by an array. Write an
element at the kth position of algorithm to insertae
Answer:
the array. WBUT 2015]
static int head, tail; //
of queue Declare global indices to head
static char
and
ta
theQueue [MAX_SIZE]; /7 The queue
//-=--~------
11 Function: InitQueue ()
// Purpose: Lnitiaize queue to empty.
1/ Returns: void
/1---
void InitQueue()
head =
tail = -1;
1 Function: Enqueue()
11 Purpose: Enqueue an item into the kth position of queue.
I Returns: TRUE if enqueue was successful
or FALSE if the engueue failed.
**
int c
/1 Check to see if the Queue is ful1l
if (isFull ()) return FALSE;
9. Write
the algorithms for PUSH and POP for linked representation of
stack.
Answer:
[WBUT 2019]
Refer to Question No. 6 of Long Answer Type Questions.
DSA-19
PQPULAR PuBLIGATIONS
2nd
Part:
A priority queue is an abstract data type that supports the
following three operations:
insert WithPriority: add an element to the queue with an associated priority it
getNext: remove the element from the queue that has the highest priority, and return
structure is as below*/
/C implementation using array of size MAX. Assume
struct data
int val,.p, O;
)d[MAX] ;
if(rear==MAX-1)
printf("Priority Queue is Full");
else
rear++t;
d[rear] =d1;
'if (front==-1)
front=0;
data temp;
for (int i=front; i<=rear; i++)
for (int j=i+1:J<=rear;jt+)
DSA-20
DATASTRUCTURE &k ALGORITHM
if (dlil .p==d[jl p)
if (d[il.o> dljl.o).
temp=d[il;
d[il=d[il:
d[j]=temp
data getNext ()
data di1;
if (front==-1)
printf ("Priority Queue is Empty");
els
d1=d[ front];
if(front==rear)
front=rear=-1;
else
front++;
return dl;
topStack has higher precedence over the scanned character Pop the stack else Push
the scanned character to stack. Repeat this step as long as stack is not empty and
topStack has precedence over the character.
Repeat this step till all the characters are scanned.
(After all characters are scanned, we have to add any character that the stack may
have to the Postfix string.) If stack is not empty add topStack to Postfíx string and
Pop the stack. Repeat this step as long as stack is not empty.
Return the Postfix string.
The Cfunction to convert an infix expression to it's equivalent postfix form is as given
below:
void postfix (char x[])
int :0;
while (x[i]! = '10')
if (isalpha (x [i])
printf("%c*, x[il);
else if (x[i] == ') ')
eLs Lse
it+
while (top> 0)
printf (" se*, pop());
int isp(char a)
if (a
return
=*'
(3);
I| a == '7' a == '8*)
return -1)
else if (a = ') ')
return (0);
int icp(char a)
DSA-22
&ALGORITHM
DATA STRUCTURE
if (a == '**
a
return (3);
|| ==
' | a == '*')
else if
return
else if
return
(a
(2);
(a
(4)
='+'
== . ()
||a ==
else if (a == )')
return (0)
if (rear == N-1)
CQ[++rear] = item;
if (front == -1)
front = 0;
DSA-23
POPULAR PUBLICATIONS
Else
Y=S->next->data;
temp=s->next;
S->next=temp->next;
free(temp);
return(y):
c)Use of stack
Reversing Data: We can use stacks to reverse data.
(example: files, strings). It is very useful for
finding palindromes.
Consider the following pseudocode:
1) read (data)
loop (data not, EOF and stack
not full)
1) push (data)
2) read (data)
3) (while stack notEmpty)
Loop
1) pop (data)
2) print. (data)
Converting Decimal to Binary:
Consider the following pseudocode
Read (number)
Loop (number > 0)
1) digit = number
modulo 2
2) print (digit)
3) number number 2
The problem with this code is that. it will
print the binary number backwards. ex:
19
becomes I1001000 instead of 00010011.)
DSA-24
DATASTRUCTURE & ALGORITHM
To remedy this problem,
stack. Then after instead of printing
the number is done the digit right away, we can push onto une
and print it. being converted, we pop the it
Evaluating digit out or tne sac
arithmetic expressions.
In high level languages,
analyze the expression infix notation cannot be used to evaluate
to expressions. we
technique 1s to convert a determine the order in which we evaluate it.
infix A
n
common
done using stack. notation into postfix notation, then evaluating it. Tnis s
tte
FR
empty
IDAIALADC
FR
F R F R
insertA InsertB insertC
FR R
F R
deleteB insert D insert E
deleteA
overflow
To avoid this problem we can think an altermative representation of a queue which
prevents an excessive use of memory. In this representation elements are arranged as in a
circular fashion where the rear again points to the front. This type of queue is known
circular queues.
are shown below (in circular
So the above sequence of operations can be represented
queue).
DSA-25
POPULAR PUBLICATIONS
T empty
FR F R
insert A insert B insert C
FR
deleteA delete B insert D insert E
As we can see that the overflow issue in the previous case while inserting E is resolved
by redirecting the rear to the front. This is the essence of circular queue.
ii) Let us now write the insert and delete functions of the circular queue implementation.
Let us also assume that F and R represents front and rear pointers respectively
void coInsert (int item)
if (rear == N-1)
int x;
if (front ==- 1)
return;
7. What are the differences between stack and- Queue? Write the algorithm for
insertion and deletion in a circular Queue. WBUT 2013
Answer:
Part: Refer to Question No. 1(" Part) of Long Answer Type Questions.
2 No. of Long
Part: Refer to Question Questions.
5 Answer Type
DSA-28
DATASTRUCTURE &ALGORITHM
Input
Operation Stack contents
token
Push on the stack top on the right)_ Details
3
16 Push on the stack
2 Push on the stack 3,116
3, 16, 2
Add 3, 18 Pop two values: 16 and 2 and push the
result 18 on the stack
Multiply Pop two values: 3 and 18 and push the
54
12 Push on the stack result 54 on the stack
54, 12
6 Push on the stack 54, 12, 6
a b
Stack Output
*", so
Next a is read. The top entry on the operator stack has lower precedence than
"*'
abe Output
Stack '*' and place it on
Checking the stack, we find that we will pop a
The next symbol is a +'.
which is not of lower
the output, pop the other +',
stack, and then push the +'
but equal priority, on the
a be**
Output
Stack
DSA-29
POPULARPUBLICATIONS
abc*+d
Stack Output
We continue by reading a * Since open parentheses do not get removed
exCent
when a closed parenthesis is being processed, there is no output. NeXt,
output. "e read and
is
Stack
L abc+de
Output
The next symbol read is a +. We pop and output **
and then push "*. Then we read
and output.
+ a bc*+d e f
Stack Output
abc+d e* f+
Stack Output
We reada "*' next; it is pushed onto the stack. Then "g" is read and output.
abc+d e* f+8
Stack Output
DSA-30
&ALGORITHM
DATASIRUCTURE
The input is now empty, so we pop and output symbols from the stack until it is enpy
e* f+s**
abe*+d
Stack Output
9. Convert the infix expression 9+ 5*7-6^2 +15/3 into its equivalent postix
expression and evaluate that postfix expression, clearly showing the
stack. WBUT 2017]
stateote
Answer:
95
95
957
957+
957*+6
957+6
957+62
957+62
957+6215
957+6215
957+62153
NONE NONE 957+62^153/+
DSA-31
POPULAR PUBLICATIONS
LINKED LIST
Chapter at a Glance
can be represented as a chain
Singly linked lists: A linked list is a data structure where data
of nodes. Each node of a linked list contains two
parts: one is the adaresS part another is the
data part. The address part holds the address of the
node which is next to or previous to the
current node. node. If the head node is destroyed
Typically the first node of a linked list is called the HEAD
on the traversal requirement a linked list
then the entire list gets destroyed as well. Depending
can be designed as circular, bi-directional ctc. In it's
simplest form the following diagram
also known as singly linked list.
shows the structure of a uni-directional linked list
Traversing, Searching)
Several operations: (Insertion, deletion,
manner is given below:
Insertion: The algorithm for inserting in the above
Let us asume that x is data value to be inserted
after the node containing the data value y. p
initially contains the address of the head node.
head node
Step 1: start traversing the linked list from the
is equal toy goto step 8
Step 2: if the data value of the head node not
Step 3: create a new node
node
Step 4: place x to the data field of the new
head node to the next address of the new node
Step 5: place the next address of the
by the new node address
Step 6: change the next address of the head node
Step 7: Goto Step 13
Step 8: Identify the address of the node
containing data value y as follows
Step 8a) if the data value of the next node of
p is equal topy
Step 8b) else changep by its next node address
Step 9: create a new node
Step 10: place y to the data field of the new node
Step 11: place the next address of p node to the next address
of new node
by the new node address
Step 12: change the next address of the p node
Step 13: End
the address
Circular linked list: the circular linked list, the address of the last node contains
of the first node, as shown in the figure below:
2000 2050 4000 3050
one
Doubly linked list: The node ofa doubly linked list contains two link fields, instead
of
other link
One link is used to point to the predecessor node, i.c., the previous node & the oue
used to point to the successor node, i.e., the next node. So, the two links are directed,
towards the front and another towards the back.
2000 2050 4000 3050
DSA-32
DATASTRUCTURE & ALGORITHM
Linked representation of polynomial: In general any polynon ial A(x) can be written as
A(x) = ao t+a,x+ax+ -- +a,-1x*- a,x.
Each a, x is i term of the polynomial, where x is variable, a, is its coefficient & e is the
exponent. If a=0, then the term is zero term, otherwise it is non:ero term.
4. Which type of linked List contains a pointer to the net as well as previous node
in the sequence? WBUT 2013]
a) singly Linked List b) Circular Linked List
c) Doubly Linked List d) All of these
Answer: (c)
5. Linked list is not suitable data structure for which one of the following
problems? WBUT 2014]
a) insertion sort b) radix sort
c) binary search d) polynomial addition
Answer: (c)
6.
Self-referential pointer is used in defining WBUT 2015]
a) an array b) a node of linked-list
c) a queue d) all of these
Answer: (d)
8,
Binary search is not possible for WBUT 20171
a) array b) linked list c) stack d) queue
Answer: (b)
DSA-33
POPULAR PUBLICATIONS
WBUT
using are correct 2017
9. A linear link list can be trerersed b) both (a) and (c)
a) recursion d) both (a) and (c)
are wrong
c) stack
Answer: (a)
is WBUT 2017n
structure o solve recursive problem d) none of these
10. The data used c) Stack
a) Linked list Queue
b)
Answer: (c)
WBUT 2019
11. Linked list is a b) Dynamic data structure
a) Linear data structure d) all of these
c) Self referential data stricture
Answer: (d)
WBUT 201
12.One limitation of linked list is
a) it requires huge memory space
b) it requires contiguous
memory space
sequentially
c)nodes can only be accessed randomly
d) nodes can only be accessed
Answer: (c)
DSA-34
ALGORITHM
DATA STRUCTURE &
p3-> exp = pl -> exp;
p3-> coff
-> = pl
append (p3, phead3); coff
now move to the next term in 1ist i*/
pl = p1 -> next;
*if p2 exponent tums .out to be higher than make p3 same as p2 and append to in
list
while (pl ->exp <p2 -> exp
p3-> exp p2 -> exp;
p3-> coff p2 -> coff
append (p3, phead3);
p2 p2 -> next;
now consider the possibility that both exponents are same , then we must ada uc
coefficients to get the term for the final list/
while (pl ->exp =p2-> exp )
p3-> exp = exp;
pl->
p3->coff pl->coff
= + p2-> coff
append (p3, phead3)
pl = pl->next
p2 p2->next
Answer:
1" Part: array are:
Theadvantages of linked list over an
Refer to Question No. 4 of Short
Answer Type Questions5.
2d Part:
n integer elements. The algorithm to insert a
Assuming the linked list already contans
data item Y in a linked list is as follows:
data X after a specific
*p, int y, int x)
node *insertXafterY (node
DSA-35
POPULAR PUBLICATIONS
m = p;
if (p->data == x)
break;
else
P P->next;
r->data = Y
I->next = m->next;
m->next = r;
return (g);
4.What are the advantages and disadvantages of linked list data structure over
array? WBUT 2010]
Answer:
Linked list advantages over array
1. Linked lists do not need contiguous blocks of memory; extremely large data sets
stored in an array might not be able to fit in memory.
2. Linked list storage does not need to be preallocated (again, due to arrays needing
contiguous memory blocks).
Inserting or removing an element into a linked list requires one data update, inserting
or removing an element into an array requirs n (all elements after the modified index
need to be shifted).
temp->next = temp->next->next;
return head;
Questions.
Question No. 4 of Short Answer 1ype
b) Refer to
WBUT 2012
structure?
7. What is a self referential
Answer: one of the data structures which refer to the pointer to
structure is
A self-referential
same type. For example, a linked list is supposed to be
(points) to another structure of the which is of the
structure. The next node of a node is being pointed,
a self-referential data
same struct type. For example,
(
typedef struct listnode
void *data;
struct listnode *next
}linked list;
DSA-37
POPULAR PUBLIGATIONS
In the above example, the listnode is a self-referential structure - because the *next is of
the type sturct listnode.
8. Write an algorithm to find the lagest and smallest element in a single linear list.
WBUT 2014]
Answer:
Linked List definition in C:
typedef struct linked listt
int data;
struct linked_list *next
Node:
Code to find largest amd smallest elements.
11 finds the largest and smallest in the 1ist
1/ assumes that head pointer is defined elsewhere
int MaxMinInList (int *max, int *min)
free (head);
head=NULL;
DSA-38
&ALGORITHM1
STRUCTURE
DATA
else
NULL)
while (temp->next
!
t=temp9i
temp=temp->next;
free(t->next)
t->next=NULL ;
return head;
a linked list.
algorithm to insert an element in the middle of WBUT 2015]
10. Write an
Answer:
List:
Node Structure for Singly Linked
struct nodedata;(
int
struct node *next;
= NULL;
start Singly Linked List
Insert node at middle position:
void insert_mid()
int pos,i; *temp, * temp1;
*new_node, *current, (sizeof
struct node (struct node));
new_noe= (struct node ) malloc
*
the data:"):
printf ( "nEnter
&new_node->data):
scanf( "&d",
new_node->next=NULL;
st position : ");
printf( "nEnter the
scanf("%d",&pos); +1))
if (pos>= (length()
pos > length ");
printf ("nError:
goto st;
if (start==NULL).
start=new_node;
current=new_node;
else
temp = start;
for (i=1;i< pos-1;itt))
DSA-39
POPULAR PUBLIÇATIONS
tenp temp->next;
templ=temp->next;
temp->next new_node
=
new node->next=templ;
11. What is the difference between array and linked-list? WBUT 2015]
Answer:
The primary difference between an array or ArrayList and a linked list is that the array or
ArayList permits random access into the list structure using a subscript; each data item
has a "named" storage location (named by the subscript). In contrast, with a linked list all
locations are relative to the next or previous locations. With an array or ArrayList, we can
access the 10 data item, say, with one probe to subscript 9 (indexing zero-up). With a
linked list, we cannot access the 10" item without first traversing the first nine items.
Searching through a linked list is thus inherently a sequential process.
On the other hand, because all locations are relative, additions and deletions to a linked
ist can be made without affecting any of the data items already stored in the
list.
insertions and deletions require only that the next and previous pointers be changed
exactly as needed; no data needs to be moved. When a deletion takes place, no hole
is
12. Show how linked list can be used to add the foliowing polynomials:
sx' +Sx +10x+8x+3 WBUT 20161
3x +2x+7x +8.
Answer:
Let us assume that the two polynomials (pl and p2) are represented using linked list and
the resultant is also using a linked list.
Let each node contain two integers: exp and coft.
The two linked lists already contain relevant data about the two polynomials. We will
create a linked list list3 (p3) with a single node to begin with.
Steps: We traverse the lists till one list gets exhausted
1) if the exponent of pl is higher than that of p2 then the next term in final list is
going to be the node of pl
2) if p2 exponent turns out to be higher than make p3 same as p2 and append to
final list
3) now consider the possibility that both exponents are same, then we must add the
coefficients to get the term for the final list
4) now consider the possibility that list2 gets exhausted, and there are terms
remaining only in list1. So all those terms have to be appended to end of list3.
The final solution would be 5x4 + 8x^3 + 12x^2 + 15x + 11 based on the above
algorithm.
DSA-40
ALGORITHM
DATASTRUCTURE&
43. How a polynomiíal using a
inked list? What are such as 8x +4x-9x +2x-17 can be represented over an
the advantages list 20171
antages of linkedWBUT
array? and disadvant
Answer:
1" part: a
nd
We can represent the polynomial by
a linked list, where each node conta
a pointer to the next node. So, the
diagram will be as follow:
S/8315 2-9112>0-17
2nd part: Refer to Question No. 4 of Short Answer Type Questions
WBUT 2018]
14. Compare and contrast linked list with static and dynamic array
Answer:
In coniras, Unked lists are dynamic and flexible and it can expand and contract is siZ
an static aray, memory is assigned during compile time. While in a dynamecutively
linked list, it is allocated during execution or runtime. Elements are storea coo
in arrays whereas it is stored randomly in linked lists.
Compare:
1. An array 1s the data structure that contains a collection of
similar type data ee
linked list is considered as non-primitive data structure contains a co1lecuio
whereas the
of unordered linked elements known as nodes. linear time, so t
1s
is fast, while linked list takes
2. ACCessing an element in an array
quite a bit slower. ana
size. Linked lists are dynamic and flexible and can expand
3. Arrays are of fixed
contract its size. memory
memory utilization is inefficient in an array. Conversely,
4. In addition
utilization is efficient in the linked list.
list and an
polynomial 4x° +7x° +2 be represented using a linked
15. How çan the used in this regard. WBUT 2019]
arrays should not be
array? Also explain why
Answer: list, where each node contains
deg, coef and
polynomial by a linked
We can represent the as follow:
to the next node. So, the diagram will be
a pointer
614 7302polynomial operations will consume
a lot of space. For solving
structures. Index of both the
Using array for to have two parallel data
you need
polynomial equations, perform the desired operation.
forward to
data structures move
DSA-41
POPULAR PUBLICATIONS
6) Write an algorithm to delete a node from a doubly linked list, where a nod
contains one data and two address (prev& next) portion. WBUT 2007 de
OR,
Write an algorithm for deletion ofa node froma doubly-linked list. pwBUT 2011
OR,
Write an algorithm to delete a nede having value NUM from a Doubiy linked list
WBUT 2019
Answer:
*C function*/
void deleteNode (node *n)
node np n->prev;
node *nn = n->next;
np->next = n->next;
nn->prev = n->prev;
delete n;
3x+-5x +2 by
b) Write the pseudo code C code for adding two polynomials (already given
user, no need to take input). Aleo comment on the complexity of your algorithm.
Answer: deg, coer
a) We can represent the polynomial by a linked list, where each node contains
and a pointer to the next node. So, the diagram will be as follow:
Type Questions.
b) Refer to Question No. of Short Answer
1
polynomia
Running is G(max(rS){T*Y)) Where x and y are the numbèr of terms in the
Poly1 and Poly2 respectively.
a linked-liet WBUT 2017
3. a) Write an algorithm for creating with n nodes.
Write a funetion for that purpose
b) How it can be made a circular linked-liet?
DSA-42
&ALGORITHM
STRUCTURE
DATA
Answer:
to nodes with values I to n in
1C functions showing how create a linked list with n
sequence
#include<stdio. h:
4include<stdlib.h>
/ linked list
A node
struct Node
int data;
struct Node *next;
list
D) Function that convert singly linked
/7 into circular 1inked list.
struct Node* circular (struct Node* head)
to NULL then
11 if head->next points
/7 start assign to the head->next node.
head->next = start;
return start
implement stack? WBUT 2017
4. How a linked-lists can be used to
Answer: list, we need to set the following things before
linked
To implement stack using
implementing actual operations.
with two members data and next.
Step 1: Define a Node' structure
Step 2: Define a Node pointer
top' and set it to NULL. make
by displaying Menu with list of operations and
method
Step 3: Implement the main method.
suitable function calls in the main
the Stack
push(value) - Inserting an element into
steps to inserta new node into the stack..
We can use the following
with given value.
Step 1: Create a newNode
is Empty (top=NULL)
Step 2: Check whether stack
set newNode next = NULL.
Step 3: If it is Empty, then
Empty, then set newNode + next = top.
Step 4:If it is Not = newNode.
Step 5: Finally, set top
pop0-Deleting an Element from a Stack
steps to delete a node from the stack...
We can use the following
is Empty (top=NULL).
Step 1: Check whether stack
DSA-44
&ALGORITHM
DATA STRUCTURE
DSA-45
POPULAR PUBLICATIONS
TREES
Chapter at a Glance
Tree: A tree is a finite set of one or more nodes connected by edges such that
i) There is a specially designated node called the root
i) The remaining nodes are partitioned into n (>=0) mutually exclusive disjoint sets
.Basic Terminology:
Node: Each data item in a tree is called a node. It specifies the data information & links
(branches) to other data items. In the example of Fig (1) the tree has 13 nodes.
i) Root: It is the parent of all other nodes of a tree. A root node does not have any parent
i) Degree of a node: The number of sub trees of a node is called its degree. In our example
theroot node has three sub trees (B, c, D). Hence, the degree of the root node A is 3. Degre
of B is 2. Degree of C is 1. And so on.
iv) Degree ofa tree: It is the maximum degree of nodes in a given tree. In our example the
root node A has the highest degree. Hence, the degree of the tree is 3.
) Terminal nodefs): A node with degree zero is called a terminal node(s) or leaf node(s)or
external node(s). In our example E, F, G, I are leaf nodes.
vi) Non Terminal node(s): Any node whose degree is not zero is called non-terminal node(s)
or intermal nodes or interior node(s). In our example A, B, C, D& H are the non-terminal
node(s).
vi) Path: It is a sequence of consecutive edges from the source node to the destination node.
In our example the path between A & I is given by e D) (D, H) & (H, ).
Binary tre: binary tree either empty or consists of one single vertex called the root,
A is
together with two disjoint binary trees called left sub-tree & right sub-tree. Number of
branches of any node is either zero or one or at most two.
Binary search tre: A binary search tree (BST) is a binary tree that is either empty or every
data node that forms the tree satisfies the following conditions.
i) The data in the left child ofa node is less than the data in its parent node.
ii) The data in the right child of a node is greater than the data in its parent node.
The left and right sub trees of the root are also binary search trees. The fig. shown below is a
Binary search tree.
60
Threaded Binary tree: In linked-list representation of binary trees, additional storage space
is required to store the two links of each node. The null pointers just results in wastage of
memory. To overcome this drawback, the null pointers are replaced by appropriate pointer
values called threads.
DSA-46
DAJASIRUCTURE& ALGORITHM
Answer: (c)
3. Maximum possible height of an AVL Tree with 7 nodes is
WBUT 2008, 2013, 2016,
20181
c) 5 d) 6
a) 3 b) 4
Answer: (a)
WBUT 2008, 2018]
4. A B-tree is
a) Always balanced b) An ordered tree
c) A direct tree
d) All ofthese
Answer: (d)
indexnumber of a child node is 6
5. Inarray representation of Binary tree, if the WBUT 2010, 2014]
then the index number of its present node is
c) 4 d) 5
a) 2 b) 3
Answer: (d)
tree with n nodes WBUT 2012]
The depth of a complete binary
6. c)log(n-1+1 d) log(n)+1
a) log(n+1-1 b) log (n)
Answer: (a)
a tree is 9, then the
7. In search tree , if the number of nods of
a binary WBUT 20121
minimum height of the tree is d) None of these
b) 5 c) 4
a) 9
Answer: (d)
not stack to hod nodes that are waiting
8. Which method of traversal does WBUT 2012]
to be processed:
b) Depth-first
a) Breadth first d) None ofthese
c) D- search
Answer: (a)
10. Number of all possibe binary trees with 4 nodes is- wBUT 20M4
a) 13 b)12 c) 14 d) 15
Answer: (c)
11. If the inorder and preorder traversal of a binary tree are D, B, F, E, G, H, A, C
and A, B, D, E, F, G, H, C respectively then, the postorder traversal o that trss is
a) D, F, G, A, B, C, H, E b) F, H, D, G, E, B, C, A WBUT 2014
c) C, G, H, F, E, D, B, A d) D, F, H, G, E, B, C, A
Answer: (d)
12. The number of possible dietinct binary trees wth 12 nodes is WBUT 201s
a) 4082 b) 4084 c) 3082 d) 3084
Answer: (6)
13. A binary tree has " leaf nodes. The number of nodes of degree 2 in this tres is
WBUT 2015]
a) logn b) n-1 c)n d) cannot be said
Answer: (d)
14. The minimum height of a binary tree of n nodes is WBUT 2016
a)n b) n/2 c) n/2-2 d) log, n+ 1)
Answer: (d)
15. The number of edges in a full binary tree oft height h is WBUT 2017)
a) 2-1
Answer: (c)
b) 2-1 c) 2-2 d) 2-2
16. Minimum number of nodes required to make a complete binary tree of height h
s WBUT 2017)
a) 2-1 2 c) 2+1 d) 2
Answer: (b)
17. Which one is required to reconstruct a binary tree? WBUT 2017
a) Only inorder sequence
b) Both preorder and postorder sequences
c) Both inorder and postorder sequences
d) Only postorder sequence
Answer: (¢)
18. Number of nodes in a compiete binary tree of depth kis WeUT 201
a) 2 b) 2k c) 2-1 d) None of these
Answer: (c)
19. A full binary tree with n non-leaf nodes contains WBUT 2019
a) log 2n nodes b) n*1 nodes c) 2n nodes d) 2n1 nodes
Answer: (d)
DSA-48
ALGORITHM
DATA STRUCTURE &
sb
3. Write a C language function to find the in-order successor of the root of a binary
tree. WBUT 20111
Answer:
Let the structure of any node be and let d be the root node.
struct Node
int data;
Node* lptr; // pointer to the left subtree
11 pointer to the right subtree
Node* rptr;
DSA-49
POPULARPUBLICATIONS
if (d == NULL)
return NOLL
return d;
Below are two functions - first one to find out the minimum key in the binary tree and
the second one to find the inorder successor of the root which uses first function.
Node treeminimum (Node *root, Node. *nil)
root Y:
Y Y->parentt
}
return (y);
DSA-50
ALGORITHM
STRUCTURE&
DATA
wBUT 2011
Write an algorithm to test whether a given binary tree is a
binary
4.
the
Answer: key values of
The solution is to check, for every node in the tree, the
min and max
v values
oy rsion
and the min and
nodes in its lett sub tree is less than the value of its key
in its right sub tree is greater than the value of its
key. This can be achieved e a
tree, after sansiy
to "bubble up" the min and max values of a node's sub
The idea repeat the same proe
IS
its parent node, which will in tum
the conditions above, to and solves the probiem
in D
traversal
algonthm is designed around pre-order tree
(linear) time.
Algorithm for the current node:
if left child exists
Stepl: Get the min and max values for left sub tree equal to current node's key, returm
"NO
max values are greater or
Srep: It ihe min and
BST min value to current node's key
value
Step 3: Itthere is no left child, set the exists
Get the min and max values for right sub tree if right child key, retum "Not
Step 4: equal to current node's
values are lesser or
STep 5* It the min and max
to
BST value from
1
step and the max value
tree, set the min
Step 6: If there is no right sub
current node's key value max value from step6
Return the min value from step and
1
Step 7:
WBUT 2011]
left rotate a binary tree.
5. Write an algorithm to
Answer tree).
may be a subtree of a larger u. u is
Input: A binary tree u (u obtained fromu by performing a left rotation about If
Output: A (new) binary tree subtree, an empty tree is returned.
empty or has an empty right
Algorithm:
BinTree rotateLefi( BinTree u)
rightSubtree(u) ==nil)
if(u=nil or nil;
return
VrightSubtreelu); leftSubtree(v), leftStubtree(u)) ):
buildTree(v.rightSubtree(v), buildTreel u,
return
binary tree using the Inorder and
Postorder
Construct a WBUT 2012]
6. What is binary tree? below;_
given
traversal of the node
Inorder
Postorder: DF BE1TEKHC
Answer:
1 Part: of one single vertex called the
root, together with
empty or consists
A binary tree is either subtree & nght subtree. Number of
branches of any
called left
two disjoint binary trees
either zero or one or at most two. binary heaps.
implement binary search trees and
node is
Binary trees are used to
DSA-51
.
POPULARPUBLICATIONS
2nd
Part:
ased on the postorder traversal, we find A is the root. Now, DBFE 1s the left child.and
GCLJHK is the right child of A.
The root of right subtree
would be the second last element in preorder 1.e., C. We ca
now further divide the right subtree(with C as root), giving {G} as rignt subtree
and (
HK} as left. In this way the final trees is given beloW
D
K
7. Construct an AVL tree using the below list. Show all the steps 12, 11,13, 10, 09,
15, 14, 18, 7, 6, 5,4 WBUT 2012, 2015]
Answer:
The steps are as shown below
(13
13
09 09
09
09)
DSA-52
DATA STRUCTURE & ALGORITHM
1
07)
07)
10 13
18 10
8.Prove that the maximum no. of
nodes in a binary tree of depth k is
2"-1.
Answer: [WBUT 2014]
The maximum number of nodes in a
binary tree in level is 2i (according
Hence the maximum number of theorem).
nodes in a binary tree of depth k is ,
maximum number of nodes from level 0 summation of
upto level k- 1, i.e.,
2' 2°+2' +2 + ..+2-
(--9]
21
9. For the following expression draw the corresponding expression
tree:
a+b*c-dle
[WBUT 2015]
Answer:
DSA-53
POPULAR PuBLICATION
10. a) Does a B tree grow at its leave or at its root? Why? WBUT 2016]
b) In deleting a key from a tree, when it is necessary to combine nodes?
B
Answer:
a) B Tree grows at its root (bottom up). B-trees are balanced search trees designed to
work well on magnetic disks or other direct-access secondary storage devices. In a B-
tree, new nodes are inserted into the leaf level however, if the B-tree must increase in
height, it is the root leve or top of the tree that changes. This automatically preserves the
balance of the tree and no rotation is necessary
b) If a node has the minimum number of keys, then deleting a key from the node will
cause an underflow and it would violate the B Tree property. It needs to be merged to
another node to fix the B Tree back.
11. The post-order and in-order traversal sequences of codes in a binary tree are
given below:
Post-order: D G E BHIFCA
Pre-order: DBG EACHFI
Construct the binary tree. WBUT 2016]
Answer:
Assuming in-order is given instead of pre-order
1) We first find the last node in post-order. The last node is "A", we know this value
is root as root always appear in the end of postorder traversal.
2) We search "A" in in-order to find left and right subtrees of root. Everything on
left of "A" in inorder is in left subtree and everything on right is in right subtree.
(DB.GE [CHFN
12. Construct one B-Tree of order 4 with the following data. 34, 67, 89, 90, 100, 2,
36, 76, 53, 51, 12, 10, 77, 69. WBUT 2016]
Answer:
After inserting 34, 67, 89
0034 0067 0089
DSA-54
&ALGORITHM
DATASTRUCTURE
After inserting 90
063
o034 0089 0090
After inserting 2
o067
O090 0100
0002 0034 0089
After inserting 36
0067
After inserting 76
0089
0067
After inserting 53
0089
0034 0067
0090 0100
0036 0053 0076
0002
After inserting 51
0067. 0089
0034
DSA-55
POPULAR PUBLICATIONS
After inserting 12
0034 O067 0089
Ater inserting 10
0034 0067 0089
After inserting 77
0034 0067
089
0012 051 0053 0076 0077 0090 0100
0002 0010 0036
After inserting 69
0034 O0670089
DSA-56
DATA STRUCTURE &ALGORITHM
Answer:
lpart:
DSA-57
POPULAR PUBLICATIONS
C.
mc
OO
2nd
Part:
The insertion steps are shown in the figure below:
k:
Sd. h,m
e.s.r:
DSA-58
DATASTRUCTURE&ALGORITHM
ce.I.nt
Draw the expression tree and write the In, Pre &
Post
16. What is expression tree? WBUT Z01O
traversals for the given expression tree: E = (2x +y) (5a -b)'.
order
Answer:
" Part:
in a tree like data
structure.
a represenitation of expressions arranged
An expression tree is operators.
It tree with leaves
is a operands of
as the expression and nodes contains the
Data interaction is also possible
in an expression tree.
Answer:
Implementing binary search tree.
We assume that a tree node has left
and right pointers and a key element.
X, SearchTree T)
ElementType
SearchTree Insert(
T = NULL)
if
tree */
and return a one-node TreeNode
Create sizeof( struct ):
T mallocNULL
if( T ==
FatalError( "Out of space!!!)
else
T->Element = X; = NULL;
T->Left = T->Right
else
DSA-59
POPULAR PUBLICATIONS
if X < T->Element )
Answer:
a binary tree.
non-recursive algorithm for in-order traversal of 2016
b) Write a WBUT 2007, 2010,
whose
Answer:
exists. The following is the non recursive C function
Assume that a stack ADT as a linked list with left, right and
key a
the binary tree stored
input is the root pointer of
the elements.
print_inorder (Node *root)
Node temp;
while(left ! =null)
(root)
push (stack, leftt (rootJ)
while(is Empty (stack))
temp = pop(stack);
print temp->key;
push(stack, right (temp) )
DSA-60
DATASTRUCIURE & ALCORITHM
s. )What is threaded binary tree? wBUT 2008, 2011]
Answer:
A Threaded Binary Tree is a binary right
tree in which every node that does not na t
child has a THREAD (in actual sense, this
a link) to its INORDER successor.
threading we avoid the recursive method of traversing a Tree, which makes use o Df tacks
and consumes a lot of memory and time.
struct *leftchild;
NODE
int node_value
struct NODE *rightchild;
struct NODE *thread;
tree. WBUT 2008]
delete a node from a binary search
D) Write an algorithm to OR,
a node from a binary search tree considering
from
for deleting WBUT 2019]
Write down the algorithm chilldren.
number of
possible cases of may be three possible scenarios
Answer: binary search iree there
ios:
from a
In order to delete a node DSA-61
POPULAR PUBLICATIONS
if (x <
p->data)
P p->lc;
else
P p->rc;
if (p == NULL)
a rDi
P b;
b rp->lc;|
/* At this point rp is the inorder successor of p *7
if (a !
p)
a->lc rp>rc;
rp->rc = p->rc;
if (g == NULL)
nroot rp;
else if (p == ->lc)
q->lc rpi
DSA-62
DATASTRuCTURE & ALGORITHM
rp->lc = p->lc;
else
->rc=
rp->lc
rp;
p->lC;
137 145
Answer:
RR
0
MAR)
a) Insert MARCH
NOV)
() Insert NOVEMBER
(MAY
DSA-63
POPULAR PUBLICATIONNS
MAY MAY
2
MAR NOV AUG) (NOV
MAY MAR
MAR MAR
(MAR)
MAR RL
DSA-64
ALGORITHMM
STRUCTURE &
DATA
+2
JAN
LR
MAR
DEC) MAY
R JULY)
MAY
AUG) (FEB)
(AUG) JAN) NOV
JUNE NOV
APR FEB JULY
JUNE
JAN
JAN +1
MAR
RR DEC
MAR
DEC 2 GUL)
MAY) (AUG) (FEB NOV
(AUG) (FEB)ULY
R CoCT
0
JUNEMAY)
(JUNE) (NOV) (APR
(APR)
JAN
DEC) MAR
(FEB GULY
AUG
NOV
(JUNEMAY (oCT
DSA-65
POPULARPUBLICATIONS
Magnetic disks (secondary memory) are cheaper than RAM and have higher
capacitcity.
But they are much slower because they have moving parts. B-trees ry to
read as much
information as possible in every disk access operation.
c) Insert 4, 5
Insert 58: 96 16
355
137 145
|5886 104 10
55
Insert 6:
19,72,74
Insert 19:
Insert 87:
19,72,74,87
Insert 51:
DSA-66
STRUCTURE&ALGORITHM4
DATA
72
Insert 10:
10 19 51 74 87
Insert 35: 74 87
10 19 35 72
L35 51
Insert 18:
74 37
101 15 1 7
72
35
Insert 39: 87
74
35 60
Insert 60,76,58,19:
10 18 19 19
35 58 74
Insert 45:
45 51
0 72 76 87
10 18 19
1939
search tree? WBUT 2010]
b) How an AVL tree differs from binary
OR
AVL Tree & Binary Search Tree? WBUT 2012
What are the differences between
Answer:
is either empty or in which each node satisfies
A binary search tree is a binary tree that
the following conditions:
than the parent
left child has a value smaller
The
11) The
right child has a value greater
than the parent.
TL & TR
NOW, an is a height-balanced tree. If T is a non-empty binary tree with
AVL tree
left and right subtrees respectively, then
T is height balanced if
s 9 TL&TR are height balanced TR respectively.
where hu & hg are the heights of TL&
h-h=1,
DSA-67
POPULARPUBLICATIONS
Now, an AVL tree is also a binary search tree, but it is a height balanced binars
ary s
tree. In case of binary search tree, if all the data are already sorted, then the height wea
O(n), where n is the number of elements in tree. So, then the worst case search tim b
be On). But since AVL tree is height balanced, this type of case will never OCcui
we can perform searching in O (Lgn) time. Now, to construct an AVL tree,
we haue
have to
perform some extra operations to get the tree height balanced.
c)Insert the following keys in the order given below to build them into an AVL tro.
8 12 9 11 7 6 tree.
Clearly mention different rotations used and balance factor of each node.
WBUT 2010
Answer:
RL rotation
( 12
OC RR rotation
12
RR rotation
DSA-68
ALGORITHIM
STRUCTURE&
DATA
Dinay
tree
the resultant
6. a) Given
the preorder and inorder sequence and draw
and write its postorder traversal:
Pre-order A
BDG HECE WBUT 2010]
In-order: GDH BEI A C JFK
to search a node in a binary search tree.
b) Write an algorithm
Answer: the binary tree. Here 1t s
the first node is always the root of
a) In preoraer traversal, corresponding in-order traversal. In order tne io
A in the n
We look 1or the position of
left and right subtrees are constructed. so noaes
node 1s a pivot around
which the other
will represent the left subtree, & all
example all nodes lying to the left of A
lying to the right of A will represent the right sub-tree.
The tree looks like.
CIFK
CJFK
(GDHBEI
GDH
CJFK
,
above tree is: G,H,D, I, E,B,J, K, F,C,A
ThePost Order traversal ofthe
DSA-69
POPULARPUBLICATIONS
b) p is either the root node or the node from where the search has to begin
void search (node *p, int digit)
if (p == NULL)
printf ("Error! structure
Tree not found\n");
else if (digit p->data)
==
printf ( "Number=*d\n", digit)
else if (digit < p->data)
else
search(p->lc, digit); //lc = left child
DSA-70
DATASTRUCTURE & ALGORITHM
"part:
The
steps ar as shown below:
02
02) 04)
( 05)
(03)
04
02
10
(06
DSA-71
POPULARPUBLICATIONS
The root element 4 when deleted will produce the following tree:
8. What is a B-tree? Show how the letters A to P of English alphabet can be entered
into a B-tree of order 4. [WBUT 201]
Answer:
1 Part:
AB-Tree of order m is an m-way tree in which
i) All leaves are on the same level.
ii) All internal nodes except the root have at most m nonempty children, and at least
2md
Part:
First A to H would be inserted into the root node one at a time as shown below.
ABCD E FGH
M
E all the alphabets up to
When I has to be inserted, the node will be split at and then
would be inserted as below
DSA-72
&ALGORITHM
STRUCTURE
DATA
Answer:
The first 4 nodes are inserted as follows:
0087
O030
0015
Insert 48
Insert 56, 85
C087
0087
O036
(e 0056
0056
0015 0085
0015 oo85
Insert into 72
Insert 91
0087
0050
O03g O001
0015 0085
Oo22 0050
0072
0048 9005
DSA-73
POPULAR PUBLICATIONS
Delete 48
Insert 6
o087 0087
O030
0091
0022
ooz2 O060
0050
0015
O015 004 0085
O000 0072
co0s 0072
Delete 15
O022
O03
P
O085
0091
O072
keys are
in growth of an order 4B- Tree when the following
10. a) Show the stages
inserted in the order givén: 11 55 77.16
WBUT 2014
28 49 70 86 68 19 55 22
84 82 29 97 61 10 45 Insert the following
keys
AVL tree differ from a binary search tree?
b) How does an
to build them into an AVL tree:
in the order given below 8 12 9 11 76 66 2 1 44
node.
and balance factor of eachWBUT
Clearly mention different rotation used 2014, 2019
can
Answer: is 3 and each nou
is 4, therefore maximum keys in one node
a) As order of B-tree
children.
have maximum of 4
DSA-74
ALGORITHHM
DATA STRUCTURE &
B-ree after
inserting 84, 82, 2
29 82 84
Insert 10 Insert 45
,oo82 0020 0082
Insert 28 Insert 49
co20 OCe2
0020 0082
Insert 70
00997
0010 0028 0045 0061 0088 00700084 0086
DSA-75
POPULAR PUBLICATIONS
Insert 19
0029 0043 O082
Insert 55
0010 0019 0028 0045 0055 0068 0070 0084 O086 0097
Insert 22
0049
0082
,0019 O020 0061
Insert 11
0049
0081 0082
0018O023
Insert 55
0040
0010 0011 0022 0028 0046 0056 0055 0068 0070 0084 0086 0007
DSA-76
ALGORITHHM
DATASTRUCTURE&
Insert 77
0040
OC20 006 0082
00
0O80 00|
OC10 0011 D022 0028 0045 O055 0056 o068 o070 007 084
Insert 16
+0040
0001 0082
00190029
0080 007.
0010 0011 001 0022 O028 0045 oss 0055O068 0070 0077O084
12
(o
Insert 2
00
DSA-77
POPULARPUBLICATIONS
Insert 1
Insert 44
0
9
66
00
11. a) The in-order and pre-order traversal sequence of nodes in a binary tree
are
given below:
Post-order
In-order 1EKC|FJB HEJE CgKLHDBA
GDKHL
Construct the tree.
b) Write an algorithm for inserting an element into a Binary tree with example.
WBUT 2015
Answer:
a) The last node in the postorder sequence is the root. We traverse right to left in the
postorder sequence, finding each node's position (left or right) with respect to the
previously located node in the Inorder Sequence. Using this we construct the tree as
shown below.
inorder: EICFJBGDKHLA
postorder: IEJFCGKLHDBA
()
(e) (*)
DSA-78
W
DATASTRUCTURE&ALGORITHM
int data;
struct bin_tree
" right, * left:
10
11ifval < ("tree)->data) {
12 insert(&(*tree)->left, val);
13 else ifval > (*tree)->data) {
14 insert(&(*tree)->right, val);
15
16
Explanation:
Lines 3-9] Check first if tree is empty, then insert node as root.
[Line 11] Check if node value to be inserted is lesser than root node value, then
is non-NULL left node
a.[Line 12] Call insert() function recursively while there
insert new node.
b.[Lines 3-9] When reached to leftmost node as NULL,
than root node value, then
Line 13] Check if node value to be inserted greater
is
DSA-79
POPULAR PUBLICATIONS
b) It is not possible to construct a binary tree just from pre and post order traversals of a
binary tree because only inorder traversals give the position of the sub-tree elements with
respect to the root.
If one has inorder along with pre or post order one can always construct a unique binary
tree because the pre/post order information gives you the root of the tree. Once the root of
the tree is known one can recursively construct the left and right sub-trees which are
binary trees themselves thereby making the final product unique.
DSA-80
&ALGORITHMM
STRUCTURE
DATA
O13
0010
0003
0005
0013
0010 0018
( 0003 0015
0005 (0014
int data;
struct node* 1eft;
struct node* right;
if (node == NULL)
return;
DSA-81
POPULARPUBLICATIONS
/*
then recur on left subtree */
printPreorder (node->left);
*nowrecur on right subtree */
printPreorder (node->right);
(AND
(BEGIN
BEGIN
AND CASE
After inserting DO
(BEGIN
AND (CASE
DSA-82
ALGORITHM
STRUCTURE&
DATA
inserting END
After
BEGIN
AND DO
DO
2
BEGIN END
BEGIN FOR
AND END
GOTo
) After removing DO
(CASE
BEGIN FOR
END
(Goro)
AND
DSA-83
POPULAR PUBLICATIONS
CASE
(BEGIN END
AND (GOTO
BEGIN GOTO
AND
n - of nodes of degree 2
no.
n= no +n tn2
Now, (1)
All the nodes except the root node has a branch coming into it. Let B
be the no. ol
&4
notnt+ n2n1 +2n2 +1
non2 t1
16. a)Create a binary search tree using the following data elements: WBUT 2019]
54, 60, 69, 32, 46, 25, 81, 29, 75, 78
b) Explain with example the process of deleting a node from a binary search tree.
Answer:
a)
(6
delete (20)
70 30
DSA-85
POPULAR PUBLICATIONS
2) Node to be deleted has only one child: Copy the child to the node and delete the
chid
ld
delete (30)
40
3) Node to be deleted has two children: Find inorder successor of the node. Copy
contents of the inorder successor to the node and delete the inorder successor. Note that
inorder predecessor can also be used.
50 (60
delete (50)
40 (70
80
The important thing to note is, inorder successor is needed only when right child is not
empty. In this particular case, inorder successor can be obtained by finding the minimum
value in right child of the node.
sub-tree) or +2 (it was right high and a level was lost from the right sub-trece) it
require re-balancing. This is achieved by performing a rotation about this node.
DSA-86
DATA STRUCTURE &ALGORITIM
DSA-87
POPULAR PUBLICATIONS
GRAPHS
Chapter at a Glance
A graph is a mathematical tool used to represent a physical problem. It is also used to
model networks, data structures, scheduling, computation and a variety of other systems
where the relationship between the objects in the system plays a dominant role.
Types of graph: A graph often symbolized as G can be of two types:
1. Undirected graph: where a pair of vertices representing an edge is unordered.
2. Directed graph: where a pair of vertices representing an edge is ordered.
Graph Traversal: A graph can be traversed in two ways:
Depth first search traversal: often analogous to pre-order traversal of an ordered tree.
an ordered
Breadth first search traversal: often analogous to level-by-level traversal of
tree.
Spanning Tree: Given a connected, undirected graph, a spanning tree of that graph
is a sub
can have many
graph which is a tree and connects all the vertices together. A single graph
each edge, which is a number
different spanning trees. We can also assign a weight to
tree by
representing how unfavourable it is, and use this to assign a weight to spanning
a
computing the sum of the weights of the edges in that spanning tree.
finding a path
Shortest Path: In graph theory, the shortest path problem is the problem of its constituent
weights of
between two vertices in a weighted graph such that the sum of the
edges is minimized.
are:
The most important algorithms for solving this problem
problems.
Dijkstra's algorithm solves the single-source shortest path weights may be negative.
Bellman-Ford algorithm solves the single source problem if edge
speed up
A search algorithm solves for single pair shortest path using heuristics to try to
the search.
6. BFS
a) scans all incident WBUT 2008]
b) edges before moving
scans adjacent unvisited to the other vertex
c) is same as backtracking vertex as soon as possiblee
d) none of these
Answer: (b)
7. A non-planar graph
a) 9 edges, 6
with minimum number
vertices of vertices has WBUT 2008, 2018]
c) 10 edges, 5 vertices b) 6 edges, 4 vertices
Answer: (c) d) 9 edges, 5 vertices
8. Any
connected graph with x vertices
a) x*
1 edges must have at least WBUT 2009]
b) x-1 edges
Answer: (6) c)x edges d) x/2 edges
9. Maximum number of edges in a
n-node undirected graph without
self loop is
WBUT 2010]
a) -1)
Answer: (b)
c) n-2
d (a)
2
11. A
complete directed graph of 6 nodes has..
S....*****s* WBUT 2011]
a)5 b) 10 c) 20
Answer: (b) d) 25
DSA-90
DATA STRUCTURE & ALGORITHM
107 320
weighted graph Tree 1. w74
2d Part:
Huffman's algorithm is a method for building an extended binary tree with
a minimum
weighted path length from a set of given weights. Initially construct
a forest of singleton
trees, one associated with each weight. If there are at least two trees,
choose the two trees
with the least weight associated with their roots and
replace them with a new tree,
constructed by creating a root node whose weight is the sum of the weights
of the roots of
the two trees removed, and setting the two trees just removed as
this new node's children.
This process is repeated until the forest consists of one tree.
Pseudocode
Huffman(W, n)
Input: A list W ofn (positive) weights.
Output: An extended binary tree T with weights
taken from W that gives the minimum weighted path length.
Procedure:
Create list F from singleton trees formed from elements of W
WHILE (F has more than one element) DO
Find T1, T2 in F that have minimum values associated with their roots
Construct new tree T by creaing a new node and setting Tl and T2 as its children
Let the sum of the values associated with the roots of
Ti and 12 be associated with the
root of T
Add T to FF
End DO
Huffman ztree stored in F
DSA-91
POPULARPUBLICATIONS
0 0
0
DSA-92
ALGORITHM
STRUCTURE&
DATA
Answer:
a) (i) The BFS traversal of the graph is:
Event Queue (Front to Rear) BFS
| Visit 1
Visit 2 12
Visit 3 123
Visit 6 1236
Remove 2
4
12364
Visit 364
Removee3 64
123647
Visit 7 647
Remove 6 47
Visit 5 475
1236475
Remove 4
Remove 7
| Remove 5
Done
Required BFS is 2
1
36475
(ii) The DFS traversal of the graph is:
Event Stack DFS
Visit 1
Visit 2 12 124
Visit 4
124 1245
Visit 5 1245
124
Pop 5
4
Pop 12456
Visit 6
Pop 6
Pop 2
Pop 1 124563
Visit 3
Visit 7 1245637
Remove7
Remove 3
Done
Required DFS is
1
2 4 5637.
6. Find out the DFS traversal of the following graph starting at node A.
WBUT 20161
-0HO-O
-0-00-0-0
DSA-93
POPULARPUBLICATIONS
Answer:
For DFS traversal we employ the following rules using stack
Rule 1 -
Visit the adjacent unvisited vertex. Mark it as visited. Display it
Push it in a stack.
Rule 2- If no adjacent vertex is found, pop up a vertex from the stack. (It
will pop up all the vertices from the stack, which do not have adjacent
vertices.)
Rule 3- Repeat Rule 1 and Rule 2 until the stack is empty.
Using the above rules we get can get the following traversal when starting with A:
ABEGHIJFKCD
7. Apply BFS/DFS Algorithms and find out the path of the given graph:
WBUT 2018]
Answer:
The steps involved in breadth first traversal are as follows:
| Search Steps
DSA-94
DATASIRUCTURE & ALGORITHM
[MODEL QUESTION
& Describe the Edge classification of DFS algorithm.
Answer
Consider a directed graph G = (V, E). After a DFS of graph G we
can put each edge into
one of four classes:
1. A tree edge
is an edge in a DFS-tree.
Is a
eage connects a vertex to an ancestor in a DFS-tree. Note that a self-loop
2 A back
back edge.
descendent in a DE
3. Aforward edge is a non-tree edge that connects a vertex to a
tree. different DFS
4. A cross edge is any other edge in graph G. It connects vertices in two
is the ancestor of the other.
tree or two vertices in the same DFS-tree neither of which
3. A Forward Edge
Tree Edge
to a descendant
IA
4. A Cross Edge to a
2 A Back Edge difetent node
to an ancestor
Any particular DFS or BFS of a directed or un-directed graph, each edge gets classified
as one of the above.
In a DFS of an undirected graph, every edge is either a tree edge or back edge. Here no
cross edge goes to a higher numbered or rightward vertex. The reason behind the DFS
algorithm js so important is that it defines a very nice ordering of edges of the graph.
OR,
Describe BFS algorithm. WBUT 2016
DSA-95
POPULARPUBLICATIONS
Answer:
1" Part:
Depth Pirst Search: DFS of a graph is analogous to the per-order traversal of an
ordered tree. For a given graph the DFS will have the following rules.
Rule l:
f possible, visit an adjacent unvisited vertex, mark it visited, and push it
on the stack.
Rule 2: 1f Rule fails, then if possible pop a vertex off the stack follow Rule
1
from it.
Rule 3: Repeat Rule 1
and Rule 2 until the all the vertices are visited.
Breadth First Search: BFS of a graph is analogous to level-by-level traversal of an
ordered tree.
For a given graph the BFS will have the following rules.
Rule 1: Visit all the next unvisited vertices (if any) that is adjacent to the current
vertex, and insert them into a queue one at a time on every visit.
Rule 2: 1f there is no unvisited vertex, remove a vertex from the Queue and make it the
current vertex and then follow Rule I.
Rule 3: Repeat Rule and Rule 2 until the all the vertices visited.
1
Breadth-first search (BFS) is a graph search algorithm that begins at the root node and
explores all the neighboring nodes. Then for each of those nearest nodes, it explores their
unexplored neighbor nodes, and so on, until it finds the goal.
The time complexity can also be expressed as O( |E|+|V) since every vertex and every
edge will be explored in the worst case.
Depth-first search (DFS) is an algorithm for traversing or searching a tree, tree structure,
graph
or graph. Intuitively, one starts at the root (selecting some node as the root in the
The time
case) and explores as far as possible along each branch before backtracking.
complexity is also given by OC|E|+|V|).
2nd
Part:
There are three ways by which graphs can be represented in memory.
i) Adjacency matrices.
ii) Adjacency list.
iii) Adjacency multilists
is a 2
i) Adjacency matrices: For a graph G with n vertices the ádjacency matrix
array with n x n element.
undirected zraphs
i, j] = 1, if there is an edge between i &j
i
A
& j.
A
[i,j]=0, if there is no edge between
DSA-96
STRUCTURE.&ALGORITHM
DATA
Undirected graph
3 5
2 4
X
Directed graph
aree
The adjacency matrix for an undirected graph is symmetrical i.e., diagonal elements
zero.
is connecting two vertices or
Advantage: it is possible to determine whether an edge
not.
Disadvantage:
is not complete, there will be a
lt requires n x n memory locations. If the graph
To avoid this, the
number of zero entries & this will waste the memory area.
adjacency list method is used.
There will be two entries for the same edge. This information is redundant.
DSA-97
POPULARPUBLICATIONS
Head nodes
Example
Undirected Graph
Head nodees
V,
MLMI
Directed graph
m-tagfield
m L V V L PL
V1, V2Vertex
P1, Pp-- Incident paths
DSA-98
ALGORITHM
DATASTRUCTURE &
V2
N N|N
N NI
V3
V N2
V4
NILN N3
S
N N4
NILNLN N5
Vertex
Vertex
4 N3 N5
5: N7
N6- N8
N8 NIL N8
b) Draw the minimum cost spanning tree for the graph given below and also find
its cost. WBUT 2009
-
Answer:
The tree has
edges AD, BD, CD, CE and BF.
Cost is 8.
Q
Oe
25.
Since the cost of A to C is not given in the question it is assumed that the cost is
DSA-99
POPULAR PUBLICATIONS
2. A rat has entered a checkerboard maze through one corner, whose the white
boxes are open and black boxes represent obstacles. Develop an algorithm by
which the rat can exit the maze through the opposite corner. Clearly explain the
representation of the maze and any specific data structure you have used for the
algorithm. WBUT 2011]
Answer:
Let the checkerboard maze be represented by the figure below. For simplicity we show a
4x4 checkerboard. Ai) (3,3)
(0,0) (3,0)
The maze can be represented by a n*n two dimensional array. Since black boxes are
obstacles, the rat will only travel through white boxes. So the best path to follow will be
the diagonal.
The algorithm will be as follow:
Steps:
i-0; j-0
1. Start with A(i, j)
2. While (i <n,j <n)
i=i+l
j=j+1
3. Final position A(n, n)
DSA-100
DAIASIKLUCIURE&ALOKIILIM
two give
shortest
Explain DiJKstra's algorlthm for finding the distanGs betwsen spe
3. and
a graph of your cholce having st lsast fivs nodes WBUT
noddes. Consider
2019
weight assigned to 9ach edge
Answer:
with its mínimum distance
During the algorithm execution, we'll mark every node as E
selected node), For node C, this distance is 0, Por the rest of odes,
node C (our
it starts being infinity ();
still don't know that minimum distance,
DSA-101
POPULARPUBLICATIONS
We now need to pick a new current node. That node must be the unvisited node with the
smallest minimum distance (so, the node with the smallest number and no check mark).
That's A.
And now we repeat the algorithm. We check the neighbours of our current node, ignoring
the visited nodes. This means we only check B.
For B, we add (the minimum distance of A, our current node) with 3 (the weight of the
1
edge connecting A and B) to obtain 4. We compare that 4 with the minimum distance of
B (7) and leave the smallest value: 4.
4
non
Afterwards, we mark A as visited and pick a new current node: D, which is the
visited node with the smallest current distance.
DSA-102
ALGORITHM
STRUCTURE&
DATA
E.
We repeat the algorithm again. This time, we check B and and
value with B's minimum distance (4)
= 7. We compare that
For B, we obtain 2 +5 9, compare it with
the miniu
value (4). For E, we obtain 2 +7
leave the smallest
one (9).
distance of E (infinity) and leave the smallest
We mark D as visited and set our current
node to B.
anything. We mark
non-visited neighbours, so we dont need to check
E doesn't have any
it as visited.
DSA-103
POPULARPUBLICATIONS
/*
Initialization: set every distance to INF INITY until we
discover a path
for dist[i]
i 0 to |v|
=
1
INFINITY
prev[i] = NULL
end
/* The distance irom the source to the source is defined to
zero *
=
dist[s] 0
/This 10op corresponds to sending out the explorers g the
paths, where walk
DSA-104
&ALGORITHM
DATASTRUCTURE
ep of pick path o
he ste vertex
"the V, with the shortest
corresponds
s explorer artLVing at an unexplored vertex *
to
1a (F is missing a vertex)
n pick
k the vertex, V, in U.with the shortest path to >
dd v to F
edge of v, (v1, v2)
for each name
/*The next step is sometimes given the confusing
"relaxation"
if (dist[v1] length (v1, v2) < dist [v2])
+
dist[v2] =
dst [vi] + length(vl, v2)
prev[v2] = v1
possibly update U, depending on implementation
end if
end for
end while
a DFS in graph: Refer to Question No. I(a) of Long Answer Type Questions.
DSA-105
POPULAR PUBLICATIONS
SORTING HASHING
Chapter at a Glance
A hash table data
structure is just like an array. Data is stored into
generated by a hash function. A this array at specific index
into a number in a smaller range. hash function hashes (converts) a number in a large range,
Linear search: Linear or Sequential Search is method
the list, scans the elements a where the search begins at one
end
desired record is found.
of the list from left to right (if the : begins from left) until of
the
This type of searching can
be performed in an ordered list or an unordered list.
lists that must be accessed sequentially, For ordered
such as 1inked lists or files with variable-length
records lacking an index, the average
performahce can be imprbved by giving up
element which is greater than the unmatched at the first
list. target value, rather than examining the entire
Binary Search: In Binary Search the entire sorted
list is divided into two parts. We first
compare our input item with the mid
element of the list and then restrict our attention only
the first or second half of the list depending to
on whether the input item comes left or right
the mid-element. In this way we reduce of
the length of the list to be searched by half.
Hashing: In hash tables, there is always a possibility that two
data elements will hash to the
same integer value. When this happens, eoloien eeeurs
i.e. two data members try to occupy
the same place in the hash table array. There are nethods to
deal with such situations like
Open Addressing and Chaining.
Bubble sort: Given an array of unsorted elemets, Bubble sort performs
a sorting operation
on the first two adjacent elements in the array, then
between the second & third, then between
third & fourth & so on.
Insertion sort: In insertion sort data is sorted data set by identifying an element
that is out of
order relative to the elements around it. It removes that element from the list,
shifting all other
elements up one place.
Finally it places the removed element in its correct location.
For example, when holding a hand of cards, players will often scan their cards
from left to
right, looking for the first card that is out of place. If the first three cards a
of player's hand are
4, 5, 2, he will often be satisfied that the 4 and the 5 are in order
relative to each other, but,
upon getting to the 2, desires to place it before the 4 and the 5. In that case,
the player
typically removes the 2 from the list, shifts the 4 and the 5 one spot to
the right, and then
places the 2 into the first slot on the left.
Quick sort: In Quick-Sort we divide the array into two halves. We select a pivot element
(normally the middle element of the array) and perform a sorting in such a manner that all the
elements to the left of the pivot element is lesser than it & all the.elements to it's right 15
greater than the pivot element. Thus we get two sub arrays.
Merge sort: In this method, we divide the array or list into two sub arrays or sub lists a5
nearly equal as possible and then sort them separately. Then the sub-arrays are again divided
into another sub arrays.
Heap sort:A heap takes the form of a binary tree with the feature that the maximum o
minimum element is placed in the root. Depending upon, this feature the heap is called ma
DSA-106
ALGORITHM
DATA STRUCTURE &
8. The best case time complexity of Bubble sort technique is WBUT 2010]
Onlogn) d) O(logn)
a) O(n) b)
olr
Answer: (a)
DSA-107
POPULAR PUBLICATIONS
13. The best case complexity of insertion sort is- WBUT 2011
a) o(r') b) o(nlog,n) d) O(n)
Answer: (d)
16. What will be the time complexity for selection sort to sort an array of n
elements? [WBUT 2012, 2016]
a) olog n) b) O(n log n) c) O(n) d) Ofn)
Answer: (d)
17. The best sorting technique when the data is almost sorted is WBUT 2013]
a) Selection sort b) Bubble sort c) Quick sort d) Insertion sort
Answer: (d)
DSA-108
ALGORITHM
STRUCTURE&
DATA
DSA-109
POPULAR PUBLICATIONS
Answer:
A sequential search of either a list, an array, or a chain looks at the first item, the
item, and so on until it either finds
second
a particular item or determines that the item does not
Occur in the group. Average case of sequential search is O(n)
A Dinary search of an array
requires that the array be sorted. It looks first at the middle of
the array to determine in which half the desired item can occur. The search
repeats this
strategy on only this half of the array.
The benefit of binary search over linear search becomes significant for lists over about
100 elements. For smaller lísts linear search may be faster because of the speed
of the
Simple increment compared with the divisions needed in binary search.
Thus tor large lists binary search is, very much faster than linear search, but is not
worthwhile for small lists.
Binary search is not appropriate for linked list structures (no random access for the
middle term).
DSA-110
ALGORITHMM
DATASTRUCTURE &
2nd Part:
be stored in the table &
A collision between two keys K & K' occurs when both have to
both hash to the same address in the table.
3
Part: table. In « se of
Open addressing: general collision resolution scheme for a hash
It is a
collision, other positions of the hash table are checked (a probe
sequence) until an empty
position is found.
The different types of Open addressing scheme includes
a) Linear Probing (Sequential Probing)
b) Quadratic Probing
c) Double Hashing (Re Hashing)
collisions of values of hash functions by
Linear probing is a used for resolving hash is accomplished using two
sequentially searching the hash table for a free location. This
values one as a starting value and one as an
interval between successive values in
same for all keys and known as the
modular arithmetic. The second value, which is the
found, or the entire
stepsize, is repeatedly added to the starting value until a free space is
table is traversed.
following:
The function for the rehashing is the
rehash(key)F(n+1) % k;
accommodate 9 information, and the data to
For example, we have a hash table that could
hash(key)= 27 % 9=0. Therefore, 27 is
be stored were integers. To input 27, we use
we know that 18 % 9= 0, then a collision
stored at 0. If another input 18 occurs, and
is needed. Using linear probing, we have
would occur. In this event, the need to rehash
18 can be stored in it.
rehash(key)= (18+1) %9= 1. Since is empty,
1
the
Quadratic probing:
In order to prevent collision we use quadratic
probing scheme.
Inquadratic probing, i
We start from the original hash location
locations i+14 i+2i+3*, i+4..
Ifa location is occupied, we check the
to the first table location if necessary.
We wrap around from the last table location
Let us take the following example:
Table Size is 11 (0.10)
11
Hash Function: h(x) =x mod
Insert keys (20, 30,2,13,25,24,10,9)
20 mod 11=
DSA-111
POPULARPUBLCATIONS
30 mod 11 = 8
2 mod 11 = 2
13 mod 1 1 =2 2+12=3
25mod 11 =33+1=4
24mod 1l =22+1, 2+2=6
19 mod
11 = 10
9 mod 11 =929+1, 9+2 mod 11,
9+3 mod
=7 11
The figure below shows the corresponding entries in the hash table.
3 13
4 25
5
6 24
7
9
8
30
920
10 10
3. Prove that, the best case time complexity for quick sort is O(nlogn) for input size
of fn. WBUT 2008]
Answer:
The analysis of the procedure QUICK_SORT is given by
T(N) = PN) + T(J-LB) + T(UB -J)
where P(N), T(J-LB), and T(UB-J) denote the times to partition the given table, sort the
left subtable, and sort the right subtable, respectively. Note that the time to partition a
table is ON). The worst case occurs when, at ea:h invocation of the procedure, the
current table is partitioned into two subtables with one of them being empty (that is J =
LB or J = UB). Such a situation, for example, occurs when the given key set is already
sorted.
The worst case time analysis, assuming J= LB, then becomes
Tw P(N) + Tw(0) +Tw(N-1)
=c*N +Tw(N-1)
c"N+c*(N-1) + Tw(N-2)
=c*N +c*(N-1) + c*(N-2) +Tw(N-3)
=c {(N+1)N)}/2= O(N2)
J =
The best case analysis occurs when the table is always partitioned in half, that is,
[LB+UB/2]. The analysis becomes:
DSA-112
DATA STRUCTURE &ALGORITHM
Tb P(N)+2Tb(N/2)
=c*N+2Tb(N/2)
c*N+ 2c(N/2) + 4Tb(N/4)
= c"N+2c(N/2) +
4c(N/4) + 8Tb(N/8)
(log2N)*c"N + 2log2N*Tb(1).
O(Nlog2N)
4. Give an algorithm to
search for an element in an array
using binary search.
[WBUT 2008]
What is OR,
the precondition
of performing binary
Search algorithm. search in an array? Write the Binary
Answer: WBUT 20101
Let us consider an array A
of size N = 10. The left index and right
left 0 right= (N-1) =9 index are
int binsearch (int A[0, int n,
int item)
int left = 0,
right =n -
1
int flag = 0; //a flag to
int mid = 0;
indi cate whether the element is found
while (left <= right) /7 till left and right cross each other
mid = (left + right) /2; // divide the array
if (item == A[mid])
into two halves
The same cannot be done with a linked list. One needs to write an algorithm to get the
value of the middle node of a linked list. In a linked list, one loses the ability to get the
value of any node in a constant time.
One solution to the inefficiency of getting the middle of the linked list during a binary
search is to have the first node contain one additional pointer that points to the node in
the middle. Decide at the first node if one needs to check the first or the second half of
the linked list. Continue doing that with each half-list.
WBUT 2012, 2014]
-
6. Draw a minimum heap tree frem the below list:
12, 11, 7,3, 10,-5, 0, 9,2
Now do the heep sert eperetien ever the heap tree which you have formed.
Write
the insertion sort algerithm.
Answer:
1Part:
The steps are as shown below:
-
-
.
DSA-114
ALGORITHHM
DATASTRUCTURE &
Performing sorting in min heap will result in the array being sorted in descending order
Thearray now looks like: -5, 2, 0, 7, 10, 11,3, 12, 9
The steps for sorting are:
Tree nodes: 9, 2, 0, 7, 10, 11, 3, 12 Sorted Array: -5
Tree nodes: 0, 2, 9, 7, 10, 11,3, 12 Sorted Array: -5
Tree nodes: 12, 2, 9, 7, 10, 11, 3 Sorted Aray: 0, -5
Tree nodes: 3, 2, 9, 7, 10, 11, 12 Sorted Array: 0,-5
Tree nodes: 2, 3, 9, 7, 10, 11, 12 Sorted Aray: 0,-5
Tree nodes: 3, 9, 7, 10, 11, 12 Sorted Array: 2, 0, -5
Tree nodes: 9, 7, 10, 11, 12 Sorted Array: 3, 2, 0,-5
Tree nodes: 7,9, 10, 11,
1
Pseudocode
We use a procedure INSERTION_SORT. It takes as parameters an array A[1.. n] and the
length n of the array. The array A is sorted in place: the numbers are rearranged within
the array, with at most a constant number outside the array at any time.
INSERTION_SORT (A)
FORj2 TO length[A]
.
2. DO key +AUI
{Put Ap] into the sorted sequence A[1..j-1]}
ij-1
WHILE i>0 and A[i]> key
DOAi +1]-A]
1. ii-1
8. Ai+1]-key
7.Write the pseudo code for Heap sort. WBUT 2013]
Answer:
The Algorithm for heap-sort is as follows.
#include <stdio.h>
#include <conio.h>
#define N
DSA-115
POPULARPUBLICATIONS
getch(O;
return 0;
int n)
void buildheap (int x[],
int i, val, s, f;
(i = 1; i < n; i++)
for
val = x[i];
s = i;
= (s1) / 2:
f (s>0 && x[f] < val1)
wile
x[s] = x[f];
S
f =
f(s- 1) / 2
x[s] = val;
x[l, int n)
void heapsort (int
int i, S, f, ivalue;
n 1; i > 0; i--)
for (i = -
ivalue = x[1]:
x[il = x[0];
f 0
if (i == 1
S 1
lse
S 1
if (i > 2 k& x [2]> x[1])
s 2 ivalue < x[s])
while (s >= 0 &&
DSA-116
DATASIRUCTURE.& ALGORITHHM
x[f] =
x[s];
S;
s 2 *E + 1;
if (s+1
St+;
<= i - 1 &&
if x[s] < x[s 1))
S
(s
=
> i -1)
1
x[f] =
ivalue;
The average value of T(i) is 1/N times the sum of T(0) through T(N-1)
1/N S TG),j = 0 thru N-1
TON)= 2/N (S T)) + CN
Multiply by N
NT(N) 2(S T)) + cN*N
To remove the summation, we rewrite the equation for N-1:
(N-1)T(N-1) = 2(8 TG)) + c(N-1, j = 0 thru N-2
and subtract:
NT(N) - (N-1)T(N-1) = 2T(N-1)+2cN-c
Prepare for telescoping. Rearrange terms, drop the insignificant c:
NT(N) = (N+1)T(N-1) +2¢N
Divide by N(N+1):
T(NV(N+1) = T(N-1)/N +2c/(N+ 1)
DSA-117
POPULAR PUBLICATIONSs
Telescope:
T(NV(N+1) = T(N-1)N
+2c/(N+1)
T(N-1(N) = T(N-2)/(N-1)+ 2c/(N)
TON-2 (N-1)= T(N-3)VN-2)
+ 2e/(N-1)
10. What is Load Factor? Why do we need hashing? How does a hash table allów
(1) searching? Why is prime number chosen for computing a hash function?
[WBUT 2018]
Answer:
1" Part:
Loads factor refers to the ratio of the number of records to the number of addresses
within.a data structure.
2d Part:
Hashing is used to inbox and retrieve items in a database because it is faster to find the
item using the shorter hashed key than to find it using the original value.
3 Part:
A hash table is an array containing all of the keys to search on. The position of each key
in the array is determined by the hash function, while can be any function which always
maps the same input to the same output. So, we shall assume the hash function as O(1 )
DSA-118
ALGORITHM
DATA STRUCTURE &
11. Write an aigorithm for Binary search with non-recursive funetion cal
WBUT 2019]
Answer:
int binarysearch(int[1 arr, int target) {
int left = 0;
int right = arr.length - 1;
int mid;
int res = -1
while (left<=right) {
else 1;
right = mid -
return -1;
12. Sort the fellowing data using bubble sort algorithm (show the intermediate
outputs): WBUT 2019]
12, 32, 23, 15, 34, 11, 25
Answer:
For each pass, we will move left to right swapping adjacent elements as needed. Each
pass moves the next largest element into its final position (end position).
DSA-119
POPULAR PUBLICATIONS
algorithm
Answer: divide-and-conquer paradigm. The Merge-sort
based on the
a) Merge-sort is general terms as consisting of the föllowing three steps:
can be described in divide
Otherwise,
1. Divide Step element, return S; it is already sorted.
zero or one
If given array A has containing about half of the elements of A.
A1 and A2, each
A into two arrays,
2. Recursion Step A2.
Recursively sort array A and a sorteu
Step arrays A and A into
3. Conquer back in A by merging
the sorted
Combine the elements
sequence.
DSA-120
&ALGORITHM
DATA STRUCTURE
int mid;
if (1owehigh)
return(0);
/* Merge function*/
merge (int all, int low, int high, int mid)
if (a[il<aljl)
c[k]=a [il;
k++
itt;
else
c[k]=aljl.
k++;
j++
while (i<=mid)
clk]=a[il;
k++
i+t
while (j<=high)
c[k]=a[jl:
k++
j++
ali]=c[il:
DSA-121
POPULARPUBLICATIONS
c) Selection sort Performance: Best Case is O(n) because even if the list is sorted, the
same number of selections must stil be performed.
is already
Insertion ort Performance: The best-case time complexity is when the array
sorted, and is O(n).
Step 2:
We increase the value of lett
We compare all the elements to the left of the pivot element.
We stop when there is no such element
by I each time, when an element is less than 68.
We record the latest value of left. In our example the left value is 2 ie., left-2.
DSA-122
DATASTRUCTURE & ALGORITHM
Step 3:
We compare all the elements
to the right of the pivot element. We decrease the value or
right by each time when an element
is greater than 68. We stop when there is no sucn
element.We record the latest value of right.
right=7. In our example the right value is' 1,
Step 4:
Since left<=right we swap between
a [left] and a [right]. That is between 77 and 39.
The array now looks like
45 26 39 14 68 61
97 77 99 90.
Step 5:
We further increment the value
of left and decrement the value of right byl respectively
i.c., left=2+1=3 and right=7-1 6.
We repeat the above steps until left
<=right.
We will see that at one stage that the
left and right indices will cross each other and we
will find that our array has been subdivided.
That all the elements lying to the left of the
pivot element is less than it and all to it's right are greater.
We then make recursive calls
of quick sort on this two sub arrays.
Performing optimal searches & retrieval of data at a constant time ie. O(1)
2) It increasesspeed, betters ease of transfer, improves retrieval, optimizes searching of
data and reduces overhead.
That's why hashing are sometimes referred as heuristic search method.
DSA-123
POPULARPUBLICATIONS
Linear Probing:
Refer to Question No. 2 of Short Answer Type Questions.
Chaining: In open addressing, collisions are resolved by looking for an open cell in the
hash table. A different approach is to create a linked list at each index in the hash table. A
data item's key is hashed to the index in the usual way, and the item is inserted into the
same index are simply added to the
linked list at that index. Other items that hashes to the
linked iist at that index. There is no need to search for empty cells in the primary hash
table array. This is the chaining method.
Let us consider the following elements
89, 18, 49, 58, 9, 7,
H(89)= 5 (Using Division-- Remainder Method)
H(18)=4 (Using Division Remainder Method)
H(49) 0 (Using Division- Remainder Method)
H(58) =2 (Using Division - Remainder Method)
-
DSA-124
&ALGORITHM
DATASIRUCTURE
position in HT that contains the record with key K. The function that does this calculation
iscalled the hash function, and is usually denoted by the letter h. Since hashing schemes
place records in the table in whatever order satisfies the needs of the address calculation,
records are not ordered by value. A position in the hash table is also known as a slot. The
number of slots in hash table HT will be denoted by the variable M with slots numbered
from 0 to M-1
The goal for
a hashing system is to arrange things such that, for any key value K and
Some hash function h, i = h(K) is a slot in the table such that 0 =i < M, and we have the
Key of the record
stored at HT[i] equal to K.
DSA-125
POPULARPUBLICATIONS
Hash tables are commonly used to implement many types of in-memory tables. They are
used to implement associative arrays (arrays whose indices are arbitrary strings or other
complicated objects), especially in interpreted programming languages like AWK, Pel,
and PHP. Hash tables can be used to implement caches, auxiliary data tables that are used
to speed up the access to data that is primarily stored in slower media. In this application,
hash collisions can be handled by discarding one of the two colliding entries-usually
erasing the old item that is currently stored in the table and overwriting it with the new
item, so every item in the table has a unique hash value.
A collision between two keys K&K' occurs when both have to be stored in the table&
both hash to the same address in the table.
Linear probing is a used for resolving hash collisions of values of hash functions by
sequentially searching the hash table for a free location. This is accomplished using two
values one as a starting value and one as an interval between successive valuesin
modular arithmetic. The second value, which is the same for all keys and known as the
stepsize, is repeatedly added to the starting value until a free space is found, or the entire
table is traversed.
The function for the rehashing is the following:
rehash(key)=(n+1) % k;
For example, we have a hash table that could accommodate 9 information, and the data to
be stored were integers. To input 27, we use hash(key)= 27 % 9=0. Therefore, 27 is
stored at 0. if another input 18 occurs, and we know that 18 % 9= 0, then a collision
would occur. In this event, the need to rehash is needed. Using linear probing, we have
the rehash(key)= (18+1) % 9= 1. Since is empty, 18 can be stored in it.
1
5. a) What do you mean by external sorting? How does it differ from internal
sorting? WBUT 2008, 2017, 2018]
Answer:
External sorting is the method when the sorting takes place with the secondary memory.
The time required for read and write operations are considered to be significant e.g.
sorting with disks, sorting with tapes.
Internal sorting on the other hand is defined as a sorting mechanism where the sorting
are
takes place within the main memory. The time required for read and write operations
considered to be insignificant e.g. Bubble Sort, Selection sort, Insertion sort etc.
Internal sorting is faster than external sorting because in external sorting
we have to
costly
consider the external disk rotation speed, the latency time etc. Such operations are
than sorting an array or a linked list or a hash table.
b) Write an algorithm for sorting a list numbers in ascending order using selection
sort technique. WBUT 2008, 2018]
OR,
for
Write a C function for selection sort and also calculate the time complexity
2010]
sort. WBUT
selection
DSA-126
ALGORITHM
DATA STRUCTURE &
Answer:
n selection sorting we select the first element and compare it with rest of the elements.
The minimum value in each comparison is swapped in the first position of the array
During each pass elements with minimum value are placed in the first position, ther
second then thira and so on. We continue this process until all the elements or tne aray
are sorted.
1/n denotes the no. of elements in the a array
void selecsort (int a[l, int n) (
int loc, min, temp, i, ji
for (i = 0; i < n; i++)
min = a[il;
loc = 1;
for (j =i t1i j < n; j++)
if (loc ! = i)
temp = a[il;
a[i] = a[loc];
a[loc] = temp
Answer:
equal sized arrays. A bad partition, on
a)A very good partition splits an array up into twovery different sizes. he worst partition
otner hand, splits an array up into two amays of in the other array. If the
puts only one element in one array and all other elements
as fast as merge sort. On the
partitioning is balanced, the Quick sort runs asymptotically
sort becomes a *slow sort".
other hand, if partitioning is unbalanced, the Quick
int m=(lo+hi) /2
mergesort (l0, m);
mergesort (m+ 1, hi);
merge(lo, m, hi);|
DSA-128
DATA STRUCTURE & ALGORITHM
100 90 80 70 60 50 40 30,20
100 90 80 70 60 50 40 30 20
DSA-129
POPULARPUBLICATIONS
Complexity of MergeSort
recurrence Tn) =
lf the running time of merge sort for a list of length n is T(n), then the
algorithm
27(n/2) +t cn where c is a constant. This follows from the definition of the
the n steps
(apply the algorithm to two lists of half the size of the original list, and add
taken to merge the resulting two lists).
rm)-27(+ on =2
27e 47+2cn4 27 2 +2.cn
=873en
k.cn
2 +lgnen(2' =n>k=log, m)
..
=n.r(1)+cn.lg(n)
=O(n.lgn)
WBUT 2012]
8. a) Radix Sort the following list:
189, 205, 986, 421, 97, 192, 535, 839, 562, 674
Write the Radix sort algorithm.
b) Find the time complexity of Binary Search
Algorithm.
Answer:
a) 1" Part:
INPUT 1 pass 2 pass 3 pass (sorted)
189 421 205 097
205 192 421 189
986 562 535 192
421 674 939 205
097 205 562 421
192 535 674 535
535 986 986 562
DSA-130
DATA STRUCTURE & ALGORITHM
list Y[k+1]
for (i = 0; i <= k; i++) Y[ij
while
= empty
L nonempty
let X first. record
move X to Y [key (X) ] in L
or more simply
radix sort (L)
DSA-131
POPULAR PUBLICATIONS
9. When will interpolation search be more appropriate than binary search? How
does an interpolation search work? Write an algorithm for interpolation search.
Show with an appropriate example that worst case time complexity of interpolation
search is o(n). What is the average case time complexity of interpolation search?
WBUT 2013]
Answer:
Interpolation search works better than Binary Search for a sorted and uniformly
distributed array.
Interpolation search is an algorithm for searching for a given key value in an indexed
array that has been ordered by the values of the key. It parallels how humans search
through a telephone book for a particular name, the key value by v hich the b0ok's entries
are ordered. In each search step it calculates where in the remaining search space the
sought item might be, based on the key values at the bounds of the search space and the
value of the sought key, usually via a linear interpolation. The key value actually found at
this estimated position is then compared to the key value being sought. If it is not equal,
then depending on the comparison, the remaining search space is reduced to the part
before or after the estimated position. This method will only work if calculations on the
size of differences between key values are scensible.
return MID
if(x # a,) then =
i
0
returni
On average the interpolation search makes about
log(log(n)) comparisons (if the elements
to be searched. In the
worst
unitormly distributed), where n is the number of elements
increase exponentially) it can
are
case (for instance where the numerical values of the keys
in 1,2..,999,1000,109 will take
make up to On) comparisons ( e.g., searching for 1000
1000 accesses).
WBUT 2014]
10. a) Define sorting.
b) What is a stable sorting? What is In-Place sorting?
c) Write the Pseudocode for Merge sort
implementation. What is its time
complexity?
a new element in the list
d) If the existing array is sorted and you want to insert
without disrupting the sortedness then which sorting
technique you should use?
Why?
Answer:
a) Sorting is a process by which a collection of items
is placed into which is typically
in an increasing or
based on a data field called a key. Sorting refers to ordering data
items.
decreasing fashion according to some linear relationship among the data
b) Stable sort:
is examined when determining the
When sorting some kind of data, only part of the data
sort order. The data being sorted can be represented
as a record or tuple of values, and the
key. A sorting algorithm is stable if
part of the data that is used for sorting is called the
R appears before S in the
whenever there are two records R and S with the same key, and
R will always appear before S in the sorted list.
original list, then
When equal elements are indistinguishable, such as with integers, or more
generally, any
is also not an
data where the entire element is the key, stability is not an issue. Stability
issue if all keys are different.
In-place sorting:
A sort algorithm in which the sorted items occupy the same storage as the
original ones.
These algorithms may use O{n) additional memory for bookkeeping, but
at most a
constant number of items are kept in auxiliary memory at any time.
e)1" Part: Refer to Question No. 1(a) of Long AnsSwer Type Questions
2 d Part:
Time complexity of merge sort:
Here at every step, the merge-sort considers only one array. In the next step, the
agorithm splits the array into halves and then sorts and merges them. In the k" iteration,
the algorithm splits the arrays into sub-arrays, which are 2"- in number. In worst
I
case
is log:n.
he number of steps required to break the array into sub-arrays of single elements
At each iteration the maximum number of comparisons is O(n). So, the time complexity
DSA-133
POPULAR PUBLICATIONS
are different
that it needs an additional space of O(n) for the temporary array b. There
b. It
possibilities to implement function merge. The most eficient of these is variant
and it is
requires only half as much additional space, it is faster than the other variants,
stable.
its best-case time complexity is when the array already Sorted
1S
a)Insertion Sort as
which is O(n).
11. What is hashing? Describe any three methods of defining a hash function.
2015, 2017]
WBUT
Answer:
part: Refer to Question No. 2 of Short Answer Type Questions.
2nd part:
maps the
A hash function maps keys to small integers (buckets). An ideal hash function
are evenly distributed
keys to the integers in a random-like manner, so that bucket values
even if there are regularities in the input data.
This process can be divided into two steps:
Map the key to an integer.
Map the integer to a bucket.
The following functions map a single integer key (k) to a small integer bucket value h(k).
m is the size of the hash table (number of buckets).
Division method (Cormen) Choose a prime that isn't close to a power of2. h{k) k mod
=
12. Write a C function to sort positive integers that does not compose the array
elements. WBUT 2016]
Answer:
#include<stdio.h>
#include<stdlib.h>
* structure for a node */
struct Node
int datta;
struct Node next;
/Function to insert
insertAtTheBegin (struct
a
node at the begining
Node * *start_ref,
of a linked
int data) ;
1sit */
void
DSA-134
DATA STRUCTURE &ALGORITHM
Function to bubble
sort the given linked lsit */
yoid bubblesort (struct Node *start);
Function to swap data of two nodes a
swap and b*/
yoid (struct Node *a, struct Node *b);
Function to print nodes in a given linked list */
void printList (struct Node *start);
int main()
int arr[0 = (12, 56, 2, 11, 1, 90)
int list_size, i;
DSA-135
POPULAR PUBLICATIONS
Swapped = 0;
ptrl = start;
if (ptr1->data> ptr1->next->data)
swap(ptrl, ptr1->next);
swapped = 1;
ptri = ptr1->next;
)
lptr = ptr1;
while (swapped);
calculation in
of solving a problem or
time-memory tradeoff is way a
)A space-time or
memory), or by solving a problem in very lttle
Css time by using more storage
space (or merge sort of is
long time. For example, the time complexity of
space by spending a
average but requires an auxiliary array.
and
O(niogn) in all cases i.e. best, worst, Ofn*2) for worst
O(nlogn) time complexity for best and average case and
Quicksort has
So, while sorting, depending on constraint, one
Case but does not require auxiliary space.
can choose which one to use.
WBUT 2019
16. a) Explain selection sort algorithm.
b) Write an algorithm for selection sort.
c) Compare selection sort with insertion sort.
algorithm (show the intermediate
d) Sort the following data using selection sort
outputs):
23, 12, 21, 15, 14, 50, 13.
Answer:
Answer Type Questions.
a)&b) Refer to Question No. 5(b) of Long
DSA-138
ALGORITHM
STRUCTURE&
DATA
Step 6:
13, 12, 14, 15, 21, 23, 50 no swap, 14 is in correct position
Step 7:
21, 23, 50 13, 12
12, 13, 14, 15, Swap
Done.
place digits are ordered, again retaining the previous relative ordering. After three
passes
the result is an ordered list.
bucket pass 1 pass2 pass 3
73[01 31011 |[o178
30[11 41]5 [146
8521 6[2]4, 42]6 [2169
59[3 713]0 3]01
6214 14]6 [4]15.[ 4]26
41[S 85]2 S93
42[6), 14[6]| 2[619 6 24
98(71 [7]8 730
7[8) 918]7 8]52
2619 I 5193 L[9)87
int main(void)
DSA-139
POPULARPUBLICATIONS
nt
730,
unsortedArr {N]
593); 78,
=(624, 852, 426, 987, 269, 146, 415, 301,
int i;
printf ("\nBefore Sorting: \n\n");
for (i = 0; i < N; i++)
printf ("85d", unsortedArr [il)
radixsort (unsortedArr, N);
printf ("\n\nAfter Sorting: \n");
for = (i 0; i < N; i++)
printf( "85d", unsortedArr [ i]);
getch ()
return 0;
void radixsort (int a[l, int n)
if la[il > m)
m = alil;
while (m / exp> 0)
Count++;
int bucket [10]
={0};
for (i 0; i < n; it+)=
#ifdef SHOWPASSs
printf("\nPASS 8d:", count);
print (a, n);
#endif
int i;
printf("\n");
for (i = 0; i < n; i+*)
printf( "*5d", a[il);
DSA-140
DATA STRUCTURE & ALGORITHM
d) Heap Sort:
A binary heap is a complete binary tree which satisfies the heap ordering property. The
ordering can be one of two types
the min-heap property: the value of each node is greater than or equal to the
value of its parent, with the minimum-value element at the root.
value
the max-heap property: the value of each node is less than or equal to the
of its parent, with the maximum-value element at the root.
12
17
DSA-141
POPULARPUBLICATIONS
DSA-142
DATA STRUCTURE & ALGORITHM
MISCELLANEOUSS
LMultiple Choice Type Questions
1. Recursion uses more memory
a) it uses stack instead space than iteration because WBUT 2019]
b) every recursive
of queue
call has to be stored
c) both (a) and (b)
d) none of these
Answer: (c)
if (str) (
while (*end)
++end;
-end;
while (str < end) {
tmp = *str;
*str++ *end;
end-- tmp;
Inthe above code, in the innermost while loop in each iteration, the characters pointed to
by str and end get swapped, str gets incremented to point to the next character, and
end is decremented to point to the previous one.
DSA-143
POPULAR PUBLICATIONS
First recursive call moves n-1 disks from 'from' to 'using' using 'to'. So after that call n-
1 disks are in 'using peg in order of size and the 'from' peg contains the nth disk i.e.,
'
the largest one. So, now move that disk from 'from' peg to "to' peg. Then again by the
2
recursive call moven-l disk from "using'. peg to "to" peg using 'from' peg. So, after all
these, 'to' peg contains all disks in order of size.
Let the time required for n disks is T(n).
There are 2 recursive call for n-l disks and one constant time operation to move a disk
from from' peg to 'to' peg. Let it be k.
Therefore,
Tn)=2 Tn-1) + k
T(0) = k2, a constant.
T(1)=2 k2+k
T(2) 4 k2+2k + ki
=
solveTowers(3,A,B,C)
solveTowers(1,A,B,C solveTowers(1,C,A,9)
-
4
solveTowers (1,A,C,B) 8olveTowers(1,C,B,A)
10
solveTowers (1,B,C,A solveTowers(1,A,B,C
2. Write
short notes on the following:
a) Index sequential file ordering
b) Tail
WBUT 2010, 2014]
recursion WBUT 2018)
Answer:
a) Building Indexed-Sequential Files:
The additional entries required on the File specification for an
output Indexed-Sequential
ile compared to an ordinary sequential output file)
(as are
Length of Key Field (columns 29-30)
Record Address Type (column 31) should contain K to specify that records are accessed
with record keys
DSA-145
POPULARPUBLIGATIONS
b) Tail recursion:
A function call is said to be tail recursion if there is nothing to do after the function
returns except return its value. Since the current recursive instance is done executing at
that point, saving its stalk frame is a waste. Specifically, creating a new stack frame on
top of the current, finished, frame is a waste.. A compiler is said to implement Tail
recursion if it recognizes this case and replaces the caller in place with the callee, so the
instead of nesting the stack deeper, the curent stack firame is reused. This is equivalent in
effect to a "GOTO", and lets a programmer write recursive definitions without worrying
about space inefficiency during execution. Tail recursion is as efficient as iteration.
DSA-146
QUESTION 2015
GROUP-A
(Multiple Choice Type Questions)
1. Answer any ten questions:
of a binary search tree Go
i) Which or the tollowing traversal techniques lists the nodes
order?
d) None of these
a) Post-order b) In-order c) Pre-order
major order?
a) nx-1)+i b) mx-1)+I c)m x (n-)+j d) n x (m-i) +i
GROUP-B
(Short Answer Type Questions)
2. What is the difference between array and linked-list? What is the primary criterion of performing
binary search technique on a list of data?
1" Part: See Topic: LINKED LIST,
Short Answer Type Question No. 11.
2 P'art: See Topie: SORTING & UASHING, Short Answer Type Question No. 9,
5. Suppose a queue is implemented by an array. Wite an algorithm to insert a new element at the
kth position of the array
See Topic: STACKS & QUEUES, Short Answer Type Question No. 8.
GROUP-C
(Long Answer Type Questions)
7. a) The in-order and pre-order traversal sequence of nodes in a binary tree are given below:
In-order
Construct the tree.
b) Define Hashing.
c) Describe a String reversal Algorithm.
d) Write an algorithm for inserting an element into a Binary tree with example.
a) & d) See Topic: TREES, Long Answer Type Question No. 1 1(a) & (b).
b) See Topic: SORTING & HASHING, Short Answer Type Question No. 2.
c)Sec Topie: MISCELLANEOUS, Short Answer Type Question No. 1(a).
8. a) Convert the following infix expression into equivalent postfix expression using stack.
(A+B) C-(D-EV(F +G)
b) What is dequeue?
c) How can a polynomial such as 6x° +3x' - 2x +10 be represented by a linked list?
d) For the following expression draw the corresponding expression tree:
a +b*c-dle
e) Write an algorithm to insert an element in the middle of a linked list
a) See Topic: STACKS & QUEUES, Short Answer Type Question No. 1(a).
b) See Topic: STACKS & QUEUES, Short Answer Type Question No. 3.
c)See Topic: LINKED LIST, Short Answer Type Question No. 3.
d) See Topic: TREES, Short Answer Type Question No. 9.
e) See Topic: LINKED LIST, Short Answer Type Question No. 10.
DSA-148
DATASTRUCTURE & ALGORITHM
9. a) For the Tollowing
graph find the BFS
and DFS traversal with proper aigonu
10. a) What is hashing? Describe any three methods of defining a hash function.
b) Discuss different collision resolution techniques.
a) See Topic: SORTING & HASHING, Long
Answer Type Question No. 11.
b) See Topic: SORTING & HASHING, Long Answer Type Question No. 3(e).
QUESTION 2016S
GROUP-A
(Multiple Choice Type Questions)
Answer any ten questions
1.
DSA-149
POPULAR PUBLICATIONS
so)=; n=1
sn)=f(n-1)+1/, n>1
has complexity O(In n).
See Topic: INTRODUCTION, Short Answer Type Question No. 2.
4. The post-order and in-order traversal sequences of codes in a binary tree are given below
Post-order DGEBHIFCA
Pre-order: DBGEACHFI
Construct the binary tree.
DSA-150
DATA STRUCTURE & ALGORITHM
Set Topic: TREES, Short Answer
Type Question No.
11.
5 Construct one B-Tree of
order 4 with the following
ta.
34, 67, 89, 90,
See Topic:TREES, 100, 2, 36, 76, 53, 51, 12, 10,
Short Answer Type 77, 69.
Question No. 12.
6.What is the default return type
of malloc( )? Why
append a node after a do we need to typecast it? Write an algorthm to
specified node in single
1" Part: See Topic: INTRODUCTION, linked list
2pd
Part: See Topic: LINKED LIST,
Short Answer Type Question No. 13.
Short Answer Type Question No.2(2
Part).
GROUP-C
(Long Answer Type Questions)
7. a) Why circular queue is
better than simple queue?
b) Evaluate the postfixX
expression using stack:
c) Convert the infix expression into
3, 16, 2,+,,12, 6, ,-
its equivalent prefix expression using stack:
a+bc+(d*e+f)* 8.
a)See Topic: STACKS & QUEUES,
Short Answer Type Question No. 5(b).
b)& c) See Topic: STACKS & QUEUES,
Short Answer Type Question No. 8.
8. a) Write a non-recursive algorithm to traverse a binary tree in its
inorder traversal.
b) Write a C function to find out the maximum and the minimum elements ina binary
c) Given search tree.
the pre-order sequence and the post-order sequence, why cannot you
tree?
recónstruct the
a) SeeTopic: TREES, Long Answer Type Question No. 2(b).
b) & c) See Topic: TREES, Long Answer Type Question
No. 12.
9. a) Construct
a tree from the given postfix expression abc* +de* f+g*+
b) Write a C function to sort positive
integers that does not compose the array elements.
Show how linked list can be used to add the following polynomials
5x+5x+10x +8x +3
3x +2x+7x +8.
) See Topic: TREES, Short Answer Type Question No. 13.
b) See Topie: sORTING & HASHING, Long Answer Type Question No. 12.
) See Topic: LINKED LIST, Short Answer Type Question No. 12.
DSA-151
eOPULARPUBLICATIONS
0--O-6
-0-0-0-9
c) Define Prim's algorithm for minimum cost spanning tree with example.
a) See Topic: GRAPHs, Long Answer Type Question No. 1(a).
b) See Topic: GRAPHS, Short Answer Type Question No. 6.
c) See Topic: GRAPHS, Short Answer Type Question No. 4.
QUESTION 2017
GROUP-A
(Multiple Choice Type Questions)
1. Choose the cortect alternatives for any ten of the following
i) Which of the following is non-inear data structure?
iv) Inserting an item into the stack when stack is not full is called. operation and deletion
of item from the stack, when stack is not empty is called.. peration.
a) push, pop b) pop, push c) insert, delete d) delete, insert
DSA-152
ALGORITHM
DATA STRUCTURE
&
following grapn
What is the sum of the degrees of all the vertices in the
vl
2 d) none of these
a) 19 b) 20 c)5
x)A
path is repetition
a) a closed walk with no vertex repetition b) an open walk with no vertex
repetition
d) a closed walk with no edge
c) an open walk with no edge repetition
Group-B
(Short Answer Type Questions)
2. How a polynomial such as 8x + 4x -9x* +2x-17 can be represented
using a linked list?
What are the advantages and disadvantages of linked list over an array?
See Topie: LINKED LIST, Short Answer Type Question No. 13.
4. Why circular queue is used over simple queue? Wrte an algorithm to insert an element into
circular queue.
part: See Topic: STACKS & QUEUES, Short Answer Type Question No. 5(b).
2 part: See Topic: STACKS & QUEUES, Long Answer Type Question No. 5(ii).
. The inorder and preorder tree traversals are given. Draw the binary tree.
Inorder. ABCDEFGHI
Preorder: FBADCEGIH
st possible to build up a unique binary tree when its prearder and postorder traversals are given?
See Topie:
TREES, Short Answer Type Question No. 18.
DSA-153
POPULAR PUBLICATIONSs
Group
(Long Answer Type Questions)
7. a)Write an algorithm to evaluate a postfix expression.
b) Convert the infix expression 9+5*7-6^ 2+15/3 into its equivalent postfix expression and
evaluate that postfix expression, clearly showing the state of the stack.
a) See Topic: STACKS & QUEUES, Long Answer Type Question
No. 2.
b) See Topie: STACKS & QUEUES, Long Answer Type Question No. 9.
with n nodes.
8.a) Write an algorithm for creating a linked-ist
Write function for that
purpose.
b) How can be made a circular linked-list?
it a
See Topie: LINKED LIST, Long Answer Type Question No.3.
internal sorting?
10. a) What do you mean by external sorting? How does it differ from
b) Write an algorithm for sorting a list numbers in ascending order using
bubble sort technique and
find its time complexity.
c) Find the time complexity of merge sort technique using the recurrence relation assuming the
size
11. a) What is hashing? Descrbe any three methods of defining a hash function.
b) Discuss different collision resolution techniques.
a) See Topic: RTING & HASHING, Long Answer Type Question No. 11.
b) See Topic: SORTING & HASHIRG, Long Answer Type Question No. 3(¢).
QUESTION 2018
Group-A
(Multiple Choice Type Questions)
1. Choose the correct altematives for the following
i) A B-tree is
a) always balanced b) an ordered tree c) a directed tree d) All of these
Group-B
(Short Answer Type Q0estions)
tree.
.Write an algorithm for in-order traversal of a threaded binary
Dee Topie:
TREES, Short Answer Type Question No. 2.
DSA-155
POPULAR PUBLICATIONS
3.Compare and contrast linked list with static and dynamic array.
See Topic: LINKED IST, Short Answer Type Question No. 14.
4. Wnte an algorithm to insert a data X immediately after a specific data item Y in a single linked
list
See Topic: LINKED LIST, Short Answer Type Question No. 2(2nd Part)
What is Load Factor? Why do we need hashing? How does a hash table allow O(1) searching?
5.
Why is prime number chosen for computing a hash function?
See Topic: SORTING & HASHING, Short Answer Type Question No. 10.
6. Insert the following keys into a B-Tree of given order mentioned below
a,f, b, k, h, m, e, s, r, c.
(Order 3)
s, l, r, x, c, l, n, t, u, p. (Order 5)
a.g. f, b, k, d, h, m, j, e,
See Topic: TREES, Short Answer Type Question No. 15.
Group-C
(Long Answer Type Questions)
7.What are sparse matrices? How such a matrix is represented in memory? What are the types of
sparse matrices?
Show that the function f(n) defined by
S)=1
So)=fn-1)+ for n >
matrix is 3500, then find the address of A[4, 2] for both row major and column major cases.
1(2md Part).
1s", 2nd &3d Part: See Topie: INTRODUCTION, Short Answer Type Question No.
2(1st Part).
4 Part: See Topie: INTRODUCTION, Short Answer Type Question No.
5h Part: See Topic: INTRODUCTION, Short Answer TypeQuestion No. 1(1" Part)..
What do you mean by external sorting? How does differ from internal sorting?
it
8. a)
b) Write an algorithm for sortinga list numbers ascending order using selection
in sort technique.
c) Describe Kruskal's minimal spanning tree algorithm.
Type Question No. 5(a) & (b).
a)&b) See Topic: SORTING & HASHING, Long Answer
c) See Topic: GRAPHS, Short Answer Type
Question No. 1.
DSA-156
DATA STRUCTURE &ALGORITHM
9. What is expression tree? Draw
the expression tree
for the given expression tree: E = (2x +y) and write the In, Pre &Post-order traversais
a graph Is always even. Apply BFS/DFS
(5a b).
-
Prove that the number of odd degree vertices
Algorithms and find out the path of the given grapi i
(A)
QUESTION 2019
Group A
(Multiple Choice Type Questions)
1. Choose
the correct alternatives for any ten of the following:
9 The worst
case complexity of binary search for a list having n elements is
a) log 2 b) nlog 2" c) d)n2
DSA-157
POPULAR PUBLICATIONS
Consider that n elements are to be stored. What is the worst case time complexity of Bubble
sort?
a) o(1) b) O(log 2n) c)O(n) d) o(n2)
v) The pre-requisite condition of binary search is
a) Unsorted array b) Ascending order array
c) Descending order array d) Sorted array
v The following sequence of operations are performed on a stack: push (1), push(2), pop, push
(1). push(2), pop. pop. pop, push(1) pop. The sequence of popped out values are
a) 2, 2, 1, 1, 1 b) 2, 2, 1, 2, 2 c) 2, 1, 2, 2, 1 d) 2, 1, 2, 2,2
xi) Asort wthich relatively passes through a list to exchange the first element with any element less
than it and then repeats with a new first element is called
a) insertion sort b) selection sort c) heap sort d) quick sort
DSA-158
DATASIRUCTURE & ALGORITHM
Group-B
(Short Answer Type Questions)
2 Write an algorithm for Binary search with non-recursive function call.
See Topic: SORTING & HASHING,
Short Answer Type Question No. 11.
6. Sort the following data using bubble sort algorithm (show the intermediate
outputs)
12, 32, 23, 15, 34, 11, 25
See Topie: SORTING & HASHING, Short Answer Type
Question No. 12
Group-C
(Long Answer Type Questions)
7. a) Explain Dijkstra's algorithm for finding
the shortest distance between two given nodes.
Consider a graph of your choice having at least five nodes
and specific weight assigned to each
edge.
b) What is priority queue?
DSA-159
POPULAR PUBLICATIONS
10. a) Explain linear and non- linear data structure with example.
b) Explain different types of data structure operations.
c)What is meant by algorithmic complexity?
d) What is time-space trade-off?
a) See Topic: INTRODUCTION, Short Answer Type Question No. 10.
b), c)& d) See Topic: SORTING & HASHING, Long Answer Type Question No. 15(a), (b)& ().
DSA-160