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

Data Structures & Algorithms ERE 3rd Sem

Uploaded by

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

Data Structures & Algorithms ERE 3rd Sem

Uploaded by

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

DATA STRUCTURE &

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.

Multiple Choice Typc Questions


1. Each element of an array arrl20][50] requires 4 bytes of storage. Base address of
arr is 2000. The location of arf10][10] when the array is stored as column major is
a) 2820 b) 2840 c) 4048 d) 4840 WBUT 2008]
Answer: (6)

2. In C language, malloc() returns WBUT 2009]


a) integer pointer b) structure pointer
c) null pointer d) void pointer
Answer: (c)

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)

5. In C language, arrays are stored in which representation? WBUT 2011]


a) Column major b) Row major c) Layer major d) None of these
Answer: (b)

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)

7.Which is better computing time (in analysis of algorithm)? WBUT 2013]


) Otn) b) O(2) c) O(log 2n) d) None of these
Answer: (c)
DSA-3
POPULARPuBLICATIONSs

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

c)mx (n-j)+j d) nx (m-i) *j


Answer: (b)

11. Which of the following is non-linear data structure? WBUT 20171


a) Stacks b) List c) Strings d) Trees
Answer: (d)

LShort Answer Type Questions


Let the size of the elements stored in an 8 x 3 matrix be 4 bytes each.
1.
address of the matrix is 3500, then find the address of A [4, 2] for
If
the base
both row major &
column major cases. WBUT 2007, 2018]
What is sparse matrix? WBUT 2007
OR,
What are sparse matrices? How such a matrix is represented in memory? What are
the types of sparse matrices? WBUT 2018]
Answer:
" Part:
In row major order the address will be
Loc(Alij))=Lo+ (-1)*n+G-i))*c
Therefore
Loc (A(4,2))= 3500+ ((4- 1)*3+ (2-1))*4= 3500+ (10) *4
3500 + 40 3540
In coumn-major order the address will be
Loc(Alij) = Lo+ (G-i) *m+(i-1) *c
Therefore
Loc(A(4,2)) = 3500+ ((2-1)*8+ (4-1)*4 3500+(11)*4
3500+ 44 3544

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

has the complexity O ( log n).


Define Big 0, 2, 6 notations. Explain the conceptual differences among these
three representatives. WBUT 2007]
And, Define Big O notation. WBUT 2010, 2012]

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

4. What is linear data structure? WBUT 2008


Answer:
A data structure is said to be linear if its elements form a sequence
or a linear list.
Examples:
Arays
Linked Lists
Stacks, Queues
The Operations that can be done on linear structures are:
Traversal: Travel through the data structure
Search: Traversal through the data structure for a given element
Insertion: Adding new elements to the data structure
Deletion: Removing an element from the data structure
Sorting: Arranging the elements in some type of order
Merging: Combining two similar data structures into one.

5. Prove that, O(f) +Ogtx)) = O (maxtfix),gix) WBUT 2009


Answer:
Suppose q(x) is in O(fx)+st)) then q(x) is in O(max(f), gct) because two times the
greatest of f{x) and g(x) is greater than or equal to the sum. More precisely:
x)=c(fx) + g(x)) 2c(max(Ax), g«).
Next, suppose q() is in Omax(fx), gtx)) then qtx) is in OCfx)+ g()) because the
greatest of f(x) and g(x) is less than or equal the sum of the two (assuming the two
functions are positive valued). In formulas:
q(x)=c max (f(x).g(x).h(x)) <=c (Ax) + g{x).
Hence proved.

6. What is an Abstract Data Type? What do you mean by a Dynamic Data


Structure? WBUT 2011]
Answer:
An abstract data type (ADT) is an object with a generic description independent of
implementation details. If for a particular collection of data only the structure of data and
the functions to be performed on the data is defined but the implementation is
not
defined, then such a collection of data is called Abstract data type.
In dynamic Data Structure memory allocation for the data structure
takes place at the run
time and only required amount of memory is allocated.
E.g: Link lists, Stacks, Queues, Trees
7. T(n)= 4n+ 3n log n, express T(n) in Big (O) notations. WBUT 2012]
Answer: lIn Big (O) notation the complexity is O(n).

8. Write thee difference between al 1tl and *a. WBUT 2012]


Answer:.
The main difference between multidimensional arrays (a[]{) and arrays of pointer (**a)
refers to an array of particular datatype arrays (a pointer to pointers to that datatatype) is
the fact that multidimensional arrays are rectangular data structures, with the same
DSA-8
DATA STRUCTURE & ALGORITHM
number of elements allocated
necessarily present in an for each specified dimension. This
array of pointers. constraint is nor

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

11. What are the characteristics of algorithm? WBUT 2014


Answer:
Precision the steps are precisely stated(defined).
Uniqueness - results of each step are uniquely defined and only depend on the input
and the result of the preceding steps.
Finiteness-the algorithm stops after a finite number of instructions are executed.
Input-the algorithm receives input.
Output-the algorithm produces output.
Generality- the algorithm applies to a set of inputs.

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

b) Refer to Question No. 1(2 Part) of Short Answer Type Questions.


13. What is the default return type of malloc()? Why do we need to typecast it?
WBUT 2016]
Answer:
malloc returns a void pointer (void ), which indicates that it is a pointer to a
region of unknown data type.
The (char*) or (int*) is an explicit type conversion, converting the pointer
returned by malloc from a pointer to anything, to a pointer to char or integer. This
is unnecessary in C, since it is done implicitly, and it is recommended not to do
this, since it can hide some errors.

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

such that 0s cig(n) fn) c%g(n).


Now c and c are two valid constants for n=>no:

DSA-10
DATA SIRUCTURE & ALGORITHM
where

no= 2 max 0isk-


Hence proved.

Long Answer Type 9uestions


1.Write short note on Abstract Data
Type. WBUT 2012, 2015]
Answer: Refer to Question No. 6 Short of Answer Type Questions.
Define pseudo-code.
2.
Answer: [MODEL QUESTION]
Actual purpose of using pseudo-code is that it is easier for humans
conventional programming language code, to understand than
and that it is an efficient and environment-
independent description of the key principles
of an algorithm.
Pseudo-code is an artificial and informal
language that helps programmers develop
algorithms. It is a "text-based" detail
(algorithmic) design tool.Pseudo-code is a compact
and informal high-level description
of a computer programming algorithm that uses the
structural conventions of a programming language,
but is intended for human reading
rather than machine reading. Pseudo-code
typically omits details that are hot essential for
human understanding of the algorithm, such
as variable declarations, system-specific
code and subroutines.

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

input the next grade (possibly the sentineL


LL the counter is not equal to zero
average to the total divided by the counter
Che
print the average
else
print 'no grades were entered
4. initialize passes to zero
initialize failures to zero
initialize student to one to ten
wnile student counter is less than or eual
input the next exam result
if the student passed
add one to passes
else
add one to failures
add one to student counter
print the number of passes
print the number of failures
if eight or more students passed
print "raise tuition"

DSA-12
ALGORITHM
DATA STRUCTURE &

STACKS & QUEUES

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

Multiple Choice Type Questions


1. A linear list in which elements can be added or removed at either end but not in
the middle is known as WBUT 2007, 2009, 20101
a) queue b) deque c) stack d) tree
Answer: (b)

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)

3. The number of stacks required to implement mutual recursion is WBUT 2011]


a) 3 b) 2 c) 1 d) none of these
Answer: (c)

4. Priority queue can be implemented using [WBUT 2011]


a) array b) linked list c) heap d) all of these
Answer: (d)

Reserve Polish notation is often known as


5. WBUT 20121
a) Infix b) Prefix c) Postfix d) none of these
Answer: (C)

6. The evaluation of the postfix expression WBUT 2012]


3, 5, 7,+, 12, % is
2 b) 3 d) 3.17
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)

8. The best data structure to evaluate an arithimetic expression in postfix formi


WBUT 2013]
a) Queue b) Stack c) Tree d) Linked List
Answer: (b)

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)

12. Stack cannot be used to WBUT 2015]


a) evaluate an arithmetic expression in postfix form
b) implement recursion
c) allocate resources (like CPU) by the operating system
d) convert infix expression to its equivalent postfix expression
Answer: (c)

13. The following sequence of operations is performed on a stack [WBUT 2015]


push(1), push(2), pop( ), push(1), push(2), pop( ), pop(), pop( ), push{2), pop()
the sequence of popped out values are
a) 2, 2, 1, 2, 1 b) 2, 2,1, 1,2 c) 2,1, 2, 2, 2 d) 2,1,2, 2, 1
Answer: (b)

14. The deque can be used WBUT 2016]


a) as a stack b) as a queue
c) both as a stack and as a queue d) none of these
Answer: (b)

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

LShort Answer Type Questions


1. a) Convert the following infix expression into equivalent postfix expression
using stack:
(A+B) C- (D E) (F + G). WBUT 2009, 2010, 2015]
b) What is a Max Heap? WBUT 2009]
Answer:

Symbol scanned Stack Output

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.

2. What is a priority queue? WBUT 2009, 2012, 2013, 2019]


Mention the different design options for priority queue. WBUT 2009]
Answer:
A priority queue is essentially a list of items in which each item has
associated with it a
prioríty. 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) prioríty item in the list. Items are inserted into priority queue
a
in any, arbitrary order. However, items áre withdrawn from a priority
queue in order of
their priorities starting with the highest priority item first.

DSA-16
ALGORITHM
DATA STRUCTURE
&

Two elements with the same priority are processed according to


the order in whicn tney
were added to the queue.
in a priority queue. A
Often a type of binary tree called a heap is used to store the items
a left child and a
heap has a root node (usually draw at the top) and it has two children,
associated with it, Witn
right child. Each node (parent, and left or right child) has a value
the property that the parent's value is more than either of its
children. When we add an
it. If it is more,
item to the heap we check to see if the parent's value is more or less than
until the
then we swap the child with the parent. We check again, and maybe swap again,
tree is "balanced," (i.e. that it obeys the heap property).
There are some other methods of implementing priority queue which are not so etficient.
They are
Sorted list implementation:
Unsorted list implementation: Keep a list of elements as the queue. To add an element,
append it to the end. To get the next element, search through all elements for the one with
the highest priority.

3. Define deque ? WBUT 20101


OR,
What is dequeue? WBUT 2015]
Answer:
Dequeue is a linear data structure, where insertions and deletions are made to or from
either end of the structure.

4.Convert the following infix expression to postfix notation by showing the


operator stack and output string after reading each input token:
AB +C*(D-E)- F*G WBUT 2011
Answer:
Symbol scanned Stack Output

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

queue over linear queue. WBUT 2012


b) Write the advantage of circular
OR,
WBUT 2016]
Why circular queue is better than simple queue?
OR,
WBUT 2017]
Why circular queue is used over simple queue
OR,
WBUT 2019]
What is the necessity of having circular queue?
Answer:
Type Questions.
Refer to Question Na. 5 of Long Answer
WBUT 2013
6. Evaluate the following postfix expression:
4,5,4, 2, a,+,'2, 2, a,9,3,,
Write pseudo code for evaluating postfix expression.
Answer:
1" Part:
4, 5, 4, 2, ',2,2, a,9,3, /,,-
A, +,
4,5, i6,+, ',2,2, n, 9, 3, /, *,
E4,21,2,2, a,9,3,1, ',-
84, 2, 2, a,9,3,/,,-
-
84, 4, 9, 3, 1, ",
84, 4, 3, *, -
84, 12
7 76
Type Questions
Part: Refer to Question No. 2 of Long Answer
priority queues are there? Can you consider stack as a
7. How many types of WBUT 2013]
priority queue? if yes, how?
Dynamic priority
Answer:
are two kinds of priority queue: 1) Static priority queue 2)
Mainly there
queue.

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 Enqueue (char ch, k)

int c
/1 Check to see if the Queue is ful1l
if (isFull ()) return FALSE;

I7 Increment tail index


tail++;:
for (c =MAX_SIZE 1; c >= k 1; c--)
array[c+1] = array [c];
arraylposition-11 ch;
return TRUE;

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

LLong Answer Type Questions


the oporations of
Write the difference between stack and quoue and implemont
1.
WBUT 2007]
priority queue.
Answer:
1" Part:
A Stack is a (ordered) collection of itenms, where
all insertions are made to the end of the
sequence. In principle a
sequence and all deletions always are made trom the end of the
items out in reverse order
Stack is a container of data items, from which we get data
ey have been put into the container. We can
say that the
also
compared to the or
why a stack is also called LIFO
item that has been put last in is coming first out. That's
item, which is put first in the container
(Last In First Out list). We can as well say that the
is get last out (First ln Last Out: FILO).
A Queue is a (ordered) collection of items, where all
insertions are made to the end of the
sequence. In
sequence and all deletions always are made from the beginning of the
retrieved out in the same order
principle a queue is container from which data items are
is a container that preserves the order of items
they are put in. This means that the queue
queue is taken last out
put there. We can also say that the item that is put last into the
the queue is taken
from the queue. We can also say that the item which put first into
is

first out. (First In First Out: FIFO).

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] ;

int front=rear=-1; /*initial values* /


/ insertWithPriority*/
void insert (data dl)

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 (d[il.p > dljl.p)


temp=d[il;
dlil=d[il:
dljj=temp
else

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;

2. Write an algorithm to convert an infix expression to postfix using stack.


WBUT 2008, 2018]
OR,
Write an algorithm to evaluate a postfix
expression WBUT 20171
Answer: right.
Scan the Infix string from left to
Initialise an empty stack.
. character is an operand, add it to the Postfix string. If the scanned
If the scannned the stack is empty Push the
character to stack.
character is an operator and if
stack 1s not empty, compare the
character is an Operana and tne (topStack). If
If the scanned character with tne eicent ou toP or the stack
precedence of the DSA-21
POPULAR PUBLICATIONS

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] == ') ')

while (s [top] != '(°)


printf (" sc*, pop());
pop (); // delete '(' symbol

eLs Lse

while (isp (s [topl)>= icp (x[il))


printf( *c", pop ());. push (x[il):

it+
while (top> 0)
printf (" se*, pop());

int isp(char a)

if (a
return
=*'
(3);
I| a == '7' a == '8*)

else if (a == +' a == '- ')


return (2);
else if (a == '")
return (1);
else if (a * #) '

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)

a) Define circular queue.


3. WBUT 2008, 2018)
Answer:
Refer to Question No. 5(" & 2d Part) of Long Answer Type Questions.
b) Write an algorithm to insert an item in circular queue. WBUT 2008, 2018]
Answer:
void QInsert (int item)

if (rear == N-1)

printf ( "Queue Is Full");


returi;

CQ[++rear] = item;
if (front == -1)
front = 0;

c) What is input restricted Dequeue? [WBUT 2008, 2018]


Answer:
An input-restricted Dequeue is one where deletion can be made from both ends, but input
can only be made at one end.

4. a) What is a Stack ADT?


b) Write aC function of popping an element from a stack implemented using linked
list.
c) Explain three uses of stack data structure. WBUT 2009]
Answer:
a) A Stack ADT is a (ordered) collection of items, where all insertions are made to the
end of the sequence and all deletions always are made from the end of the sequence. In
we get data items out in reverse
principle a stack is a container of data items, from which
order compared to the order they have been put into the container. We can also say that
the item that has been put last in is coming first out. That's why a stack is also
called
LIFO (Last In First Out list). We can as well say that the item, which is put first in the
FILO).
container is get last out (First In Last Out:

DSA-23
POPULAR PUBLICATIONS

b) Assume that the list is defined as below:


typedef struct node *nptr;
struct node
int data;
nptr next;
/* function pop */
Lnt pop (nptr s) /*Function to pop the elements*
nptr temp;
int yi
if (s->next==NULL)
printf( "Underflow on Pop");
return(-1);

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

What is Circular queue?


5. i)
ii) WriteQ-insert algorithm for
the circular queue. WBUT 2010]
[WBUT 20101
Write an algorithm to OR,
insert an element into circular queue.
Answer: WBUT 2017]
i) The two algorithms QINSERT&
front pointer F never manages QDELETE can be very wasteful of storage
to catch up the rear pointer. Actually an arbitrary if the
amount of memory would large
be required to accommodate the elements.
performing operations on a Queue should The method of
only be used when the queue is emptied at
certain intervals.
Let us consider the following sequence
of operations. F and R represents the front and
rear pointers.

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)

printf( "Queue Is Ful1)


return
COl++rear] = item;
if (front ==- 1)
front =
0
int coDelete ()

int x;
if (front ==- 1)

printf ( "Queue Is Empty"):


exit (0)
x CQ[front];
=
CQ[front]
if (front
1;
== rear)
=-
front
else
= rear =
.1
front++;
return x
In linear queue the condition for queue full is
QREAR-MAXLIMIT
Suppose maxlimit is ten and queue is full now if we delete 9 element from queue then
inspite of queue is empty we cannot insert any element in the queue. This wastage of
memory is solved through circular queue where queue full condition is
QREAR-Qfront+
DSA-26
DATA STRUCTURE & ALGORITHM
6. Define the ADT for stack. Show
using linked list. the implementation of the stack data structure
Answer: WBUT 2011]
The Stack ADT
has two main functions:.
Push
inpu a stack data object, an
output: a bOolean
element of the base
indicating whether type
effect: the element is the operation was successtul
added to the sequence
in the stack, in the top position
Pop
input: a stack data object
output: a boolean
indicating whether
effect: the element in the top positionthe operation was successfu
in the sequence in the stack is removed
Stack Implementation
First, let us define the linked ,
list data structure.
typedef struct
linkedIist
int data;
struct linked_list *next;
Node;

For us to beable to test our code, we need


following code uses recursion to define a way to display our
to display stack. stack. The
|/ recursively display the contents
/7 of thé stack
void DisplayStack (Node*
currentNode)
// recursive termination condition
if (currentNode == NULL)

return;

I7 the node is not null


17 display the data
printf (" -> sd", currentNode->data)
T7 recursively call the display to
display the next element in the stack
Displaystack (currentNode->next);
Thecode for pushing an element onto the stack is as given
below.
push item on the stack
this is same as adding
at the top of the list
node a
void Push (int dataToAdd)
I assumption:
program head is already derined elsewhere in the
he
1. create the new node
DSA-27
POPULAR PUBLIÇATIONS

Node *temp = new Node


temp->data = dataToAdd;

11 2. insert it at the first position


temp->next = head;

77 3. update the head to point to this new node


head temp;

The code for popping an element from stack is given w.


I pop an element from the stack
/7 this is same as removing the first. element
11 from the list
Node* Pop ()

11 check for empty list


if (head == NULL)

printf( "Stack is empty \n") ;


return NULL;

/1 get the top node


Node *firs tNode = head;
move the head
head = head->next;
// disconnect the node
11 from the list
firstNode->nextt = NULL;

Il return the top node


return firstNode;

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

8. a) Evaluate the postfix expression using stack: WBUT 2016]


3, 16, 2, +,', 12, 6, 1,
b) Convert the infix expression into its equivalent prefix expression using stack:
a+b'c+(d*e+S)*g.
Answer:
a) The steps are as shown below:
3, 16, 2, +,', 12,6, /;

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

Divide 54, 2 Pop two values: 12 and 6 and push the


result 2 on the stack
Divide Pop two values: 54 and 2 and push the
54, 2
result 52 on the stack
tokens)Keturn the result) 52 Pop the only value 52 and return it
b) First, the symbol "a" is read, so it is passed through to the output. Then +" is read and
pushed onto the stack. Next "b" is read and passed through to the output. The state of
affairs at this juncture is as follows:

a b

Stack Output
*", so
Next a is read. The top entry on the operator stack has lower precedence than
"*'

nothing is output and ** is put on the


have
stack. Next, "c" is read and output. Thus far, we

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

he next symbol read is an (, which, being of highest precedence,


the stack. Then "d" is read
is placed. on
and output.

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

Now we read a ), so the stack is emptied back to the'('. We output a '+.

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:

Symbol scanned Stack Output

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.

Multiple Choice Type Questicns


1. In a circularly linked list organization, insertion of a record involves the
modification of [WBUT 2008, 2018]
a) no pointer b) 1 pointer
c) 2 pointes d) 3 pointers
Answer: (c)

Linked list are not


2. suitable for WBUT 2012, 2016]
a) Stack b) Deque c) AVL Tree d) Binary search
Answer: (d)

Dynamic memory allocation use


3. WBUT 2012]
a) Calloc b) Malloc c) Free d) all of these
Answer: (d)

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)

Inserting a node after a given node in a doubly linked list requires


7.
WBUT 2016, 2018]
a) four pointer exchanges b) two pointer exchanges
c) one pointer exchange d) no pointer exchangge
Answer: (b)

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)

Short Answer Type Questions


WBUT 2007
algorithm to add wo polynomials.
1. Write an
Answer: and the resultant
assume that the two polynomials are represented using linked list
Let us
is also using a linked list. lists under
phead1, phead2 and phead3 represent the pointers of the three
Let
consideration.
exp and coff.
Let each node contain two integers: the two
assume that the two linked lists already contain relevant data about
Let us
polynomials. of th
append to insert a new node at the end
Also assume that we have got à function
given list.
pl = phead1;
p2 phead2;
p3 to build the third list
Let us call malloc to create a new node
p3 phead3;
list gets exhausted */
now traverse the listsIl till oneNULL))
while ((pl !=NULL) (p2!=
list is
if the exponent of pl is higher than that of p2 then the next term in tinai
going to be the node of pl*/
while (p1 ->exp p2> exp

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

list2 gets exhausted, and there are terms remaining


now consider the possibility that
have be appended to end of list3. However, one does
only in listl. So all those terms to
pointing to remaining terms, so simply
nothave to do it term by term, as pl is already
append the pointer pl to phead3 */
if ( pl != NULL)
append (p1, phead3)
else
append (p2, phead3);
list over an array? WBUT 2008]
What are the advantages of linked
2.
X after a specific data item Y in a linked list.
Write an algorithm to insert a data [WBUT 2008, 2016, 2018]

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

node *q, *r, m


=
P:
r (node* ) malloc (sizeof (node));
while (p->next != NULL)

m = p;
if (p->data == x)

break;

else
P P->next;

r->data = Y
I->next = m->next;
m->next = r;
return (g);

3. How can a polynomial such as 6x°+4x* -2x+10 be represented by a linked


list? WBUT 2010, 20151
Answer:
We can represent the polynomial by a linked list, where each node contains deg, coef and
a pointer to the next node. So, the diagram will be as follow:

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).

Linked list disadvantages over array:


. Arrays have contiguous memory allocation which makes it easy to access elements in
between.
2. As memory is allocated during compilation makes the program faster
3. Fixed in size so if we are aware of the exact size of datas then there ean be no
memory wastage which is also an advantage linked list has.
DSA-36
ALGORITHM
STRUCTURE &
DATA

is easy but not in between.


4. Insertion and deletion at the end of the array
5. Accessing data is easy. Example, a[2].
a singly-linked list.
The
5. Write a C language function to delete nth node of WBUT 2011]
conditions are to be handled properly.
Answer: int n)
node* DeleteNode (struct node* head,
struct temp head;
struct node* =

int length LinkedListLength( temp );


int i:
n length) (
if (nprintf(
<= 0 || >
"ERROR: Node does not exist! \n");
}else(
if (n == 1) ( (1st node) to
nead = head->next; //move from head
seçond node
else 1; i < n-1; ++i) //move through
1ist
for (i temp temp->nextt

temp->next = temp->next->next;

return head;

+3 can be represented using a linked list? 2012]


a) How the
polynomial 4x -10x linked list. WBUT
6. array and a single
b) Compare and contrast between an
Answer: linked list, where each node
contains deg, coef
polynomial by a
a) We can represent the díagram will be follow:
as
next node. So, the
and a pointer to the

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)

/ start at the root


Node *currentNode head;
if (currentNode == NULL)
return 0: // 1ist is empty
11 initialize the max and min values to the first node
*max = min = currentNode->data;
/ loop through the list
for (currentNode = currentNode->next; currentNode != NULL;
currentNode = currentNode->next)

if (currentNode->data > *max)


max= currentNode->data;
else if (currentNode->data < *min)
*min = currentNode->data;
// we found our answer
return 1;

9. Write an algorithm to delete the last node of a linked-ist. WBUT 2015


Answer:
C function to delete last node is as given below:
struct node *delete (struct node *head)

struct node *temp =head;


struct node *t;
if (head->next==NULL)

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

lef. The deleted node becomes unused memory.

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

Long Answer Type Puestions


1. a) How can a polynomial
such as 5r' -3x +9x-1| be represented by a i
list? WBUT inked
Answer: 200n
we can represent the polynomial by a linked list, where each node contains
eticient and a pointer to thè next node. So, the diagram will be as follow: g
deo

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;

2. a) Represent the given polynomial using a link list. WBUT 2014

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;

a reference (pointer to pointer) to the head


/Given l1st an int, appends a'new node ,at the end
of a and
yoi append ( struct Node** head _ref, int new_data)

/* 1. allocate node */ (struc


new_node = (struct Node*) malloc (sizeof
struct Node*
Node));
struct. Node *last = *head_ref; /*used in step 5*/

7* 2. put in the data */


new _node->data = new_data;
last node, o make
new node is going to be the
3. This
next ofE
it as NULL*/7
new_node->next = NULL;

is empty, then make the new node as


4. If the Linked List
head /
if (*head ref == NULL)

*head_ref = new node;


return1;

the last node */


*5. traverse till
Else NULL)
while (1ast->next !=
last = last->next;
last node */
6. Change the next of
Last->next = new_node;
return
this creates a list*7
int createList0
DSA-43
POPULAR PUBLIGATIONS

/* Start with the empty list *


struct Node* head = NULL;
for (i=0; i<n; i++)
/1 Insert data, at the end
append (&head, i);

list
D) Function that convert singly linked
/7 into circular 1inked list.
struct Node* circular (struct Node* head)

7declare a node variable start and


head node into start
node.
assign
= head;
struct Node* start
equal
1check that while head->next not node.
head points to next
to
while
NULL then
(head->next != NULL)
head = head->next;

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

If it is Empty, then display "Stack is Empty!! Deletion is not poSsibi e".*


Step 2:
terminate the function
Step 3: f it is Not Empty, then define a Node pointer 'temp' and set it to
top.
Step 4: Then set top top
= next.
Step 7: Finally, delete 'temp' (free(temp).

5. Write short notes on the following: WBUT 2013]


a) Linear Lists WBUT 2015]
b) Circular link list
Answer:
a) Linear Lists: denoted as the
A pe, usually
linear list stores a collection of objects of a certain
list in a linear sequei
elements of the list. The elements are ordered within the linear
Linear lists are usually simply denoted as lists. at a
Unlike an array, a list is a data structure
allowing insertion and deletion of elements
in question is given, for exampi
arbitrary position of the sequence. If the position 1s, no
a modification takes only a constant number of operations, that
reference, such an
necessary and all insertion and deletion operations take
eftortful copying of entries is
access a single element va a
Conversely, however, one cannot
equally short time. for it
constant time, as in the case-of an array, without having searched
integral) index in limited to a certain
received a reference to it. Furthermore, lists are not
before and having
beginning on (like an array).
maximum number of elements from the

b) Circular link list:


2 Categories.
Circular Linked List is Divided into
List
o Singly Circular Linked
o Doubly Circular
Linked List "First
List Address field of Last node contain address of
Circular Linked
In
Node".
In short First Node and
Last Nodes are adjacent.
likecircular
made circular by 1inking first and last node, so it looks
Linked List is
diagram.
chain as shown in following
Start

possible only if we are using "Doubly Circular Linked List"


Two way access is
possible
Sequential movement is
allowed.
No direct access is

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

Multiple Choice Type guesions


NULL link of any noa is
a right
1. If a binary tree is threaded for in-order traversal WBUT 2007, 2016]
replaced by the address of its d) own
a) successor b) predecessor c) root
Answer: (a)
of every node never 2018]
dinTer
2. In a height balanced tree the heights of two sub-tmes 2009,
WBUT 2007,
by more than d)--1
a) 2 b) 0 c) 1

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)

9.Which of the following is essential for


converting an infix expression to the
WBUT 2013]
postfix expression efficiently?
a) An operator stack
b) An opeand stack
A tree
c) An operand stack and operator stack
d) parsi
Answer: (a)
DSA-47
POPULAR PUBLICATIONS

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 &

Short Answer Type Questions


1. Construct the expression tree WBUT 2010]
for the following expression:
E = (2a +5b)(x-7»)
Answer:
Q

sb

2. Write an algorithm for non-recursive in-order traversal of a threaded binary tro.


WBUT 2011, 2018]
Answer:
Step-1: For the current node check whether it has a left child which is not there in the
visited list. If it has then go to step-2 or else step-3.
Step-2: Put that left child in the list of visited nodes and make it your current node in
consideration. Go to step-6.
Step-3: For the current node check whether it has a right child. If it has then go to step-4
else go to step-5
Step-4: Make that right child as your current node in considération. Go to step-6.
Step-5: Check for the threaded node and if it's there make it your current node.
Step-6: Go to step-1 if all the nodes are not over otherwise quit

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;

Node* successor (Node * d)

DSA-49
POPULARPUBLICATIONS

if (d == NULL)
return NOLL

1/ If d has a Right Child


if (d->rptr != NULL)

// Move to Right Node


d = d->rptr;

IwhileMove to the extreme left


(d->lptr != NULL)
d = d->lptr;

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)

/* returns a pointer to the minimum key in a NONEMPTY tree *

while (root->left != nil)


root =
root->left
return(root);

Node * treesuccessor (Node *root, Node *nil)

* returns to inorder successor of root, and to


pointer
nil if root is the maximum of the tree. This code
assumes that root ! nil. */
Node *treeminimum (Node *, Node *);
Node *yY;
if (root->right != nil)
return (treeminimum (root->right, nil));
y
=
root->parent;
while (y != nil && root == y->right)

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

3) We recur the above process for two subtrees.

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 100


0067

0034 O089 O090 0100

After inserting 2
o067

O090 0100
0002 0034 0089

After inserting 36
0067

0089 0090 0100


0002 0034 036

After inserting 76
0089
0067

0076 0090 0100


0002 0034 0036

After inserting 53
0089
0034 0067

0090 0100
0036 0053 0076
0002

After inserting 51
0067. 0089
0034

0076 0090 0100


0051 0053
0002 0036

DSA-55
POPULAR PUBLICATIONS

After inserting 12
0034 O067 0089

0002 0012 0036 0051 0053 0076 0090 o100

Ater inserting 10
0034 0067 0089

0002 0010 0012 0036 005 1 0053 0076 0090 0100

After inserting 77
0034 0067
089
0012 051 0053 0076 0077 0090 0100
0002 0010 0036

After inserting 69
0034 O0670089

0053 0076 0077 0090 0100


0002 0010 0012 0036 0051 0069

13. Construct a tree from the glven postfix expression


abe* +de*f +8+
WBUT 2016]
Answer:

Postcode traversal: a bc* +de*f+g*+


are glven. Draw the binary tree.
14. The inorder and preorder tree traversale
Inorder: ABCDEFGHI
Preorder: FBADCEGIH
le it possible to build up a unique
binary tree when its preorder and postorde
weUT 2017
traversals are given?

DSA-56
DATA STRUCTURE &ALGORITHM
Answer:
lpart:

part: Refer to Question No. 12(b) (1*


Part) of Long Answer Type Questions.
16. 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)
a,9.4, b, k, d, h, m, j, e, s, 1, r, x, c, \, n, t, u, p.
(Order 5) WBUT 2018]
Answer:
l" part:
Construction of B-tree: (of order 3)
a,f,b, k, h, m, e, s, r, C

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.

Long Answer Type Questions.


d Part: Refer to Question No. 2(a) of

Long Answer Type Questlons


in a binary search tree. WBUT 2007, 20141
1. Write an algorithm to insert a node

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 )

T->Left = Insert ( X, T->Left


el Lse
if( X > T->Elementt )i
T->Right = Insert ( X, T->Right do nothing */
is in the tree already: we'll *7
Else X
this 1ine!!
return T; /* Do not forget

tree for the expression E = (2x+y)*(5a -b).


2. a) Construct an expression WBUT 2007

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.

The tree has 6 null links


2 each for the leaf nodes.
In-order traversal of the
tree is C B DA E.

consider the tree show above.


Let us
the left child of C, which
The immediate predecessor of C will be the head node. So Head node
null link, will point to the
is a
head node. (as per in-order
traversal)
The right null link of C wil
point to the immediate successor
which is B (as per in-order
traversal).
point
The left null link ofD will
predecessor
to the immediate
traversal).
which is B (as per in-order is A (as per in-
D will point to the immediate successor which
The right null link of
order traversal). resultant threaded
followed for the node E also and we get the
The above procedure is
like this-
binary tree.
threaded binary tree varies a bit and its
The node structure for a
struct NODE

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

1. Node to be deleted has no children


2. .The node to be deleted
has only one sub tree
3. The node to be deleted
has both left & right subtrees
node *delete (node *p, int x)

node *g, *rp a *b *root;


NULL;
root =
Pi
while (p!= NULL & &x != p->data)

if (x <
p->data)
P p->lc;
else
P p->rc;

if (p == NULL)

printf("key not present");


exit(0)

if == NULL) /* node p has


(p->lc no left child*
IP P->rc;
else if (p->rc == NULL) p has no right child'/
rp = P->lc;
else

a = p; /* a contains the parent node p */


rp = P->rc;
b rp->lc; /* b is always left child of rp *
while (b ! = NULL)* to find the inorder successor with no
left child */

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;

free (p): // delete the node


return (root) ;

4. a) Show the steps in


creation of a height balanced binary AVLL TREE using
insertion of items in the following
(March, May, November, August,
order -
Show the balancing steps required.
April, January, December, July, February,June,
October, September)
b) What do you mean by a B-Tree
WBUT 2009]
what are the uses of such a tree in data
and
structures? WBUT 2009]
OR,
For what purposes are B trees especially appropriate?
WBUT 2016]
c) Consider a B-Tree of order 5 as shown below
insert the elements 4, 5, 58, 6 in
this order in the B-Tree. WBUT 2009]
89616

137 145

Answer:
RR
0

MAR)
a) Insert MARCH
NOV)
() Insert NOVEMBER

(MAY

(b) Insert MAY


d)Insert AUGUST

DSA-63
POPULAR PUBLICATIONNS

MAY MAY
2
MAR NOV AUG) (NOV

(AUG APR (MAR

APR (e) Insert APRIL

MAY MAR

AUG (NOV AUG MAY

MAR) (APR JAN (NOV

(JAN () Insert JANUARY

MAR MAR

(AUG MAY AUG MAY


0

APR JAN (NOV)APR JAN NOv

(DEC (DEC) JULY

(g) Insert DECEMBER Ch) Insert JULY

(MAR)
MAR RL

AUG MAY DEC MAY


NOV)
APR JAN (NOV) AUG JAN
(APR
JULY
DEC) JULY B)

FEB (i) Insert FEBRUARY

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)

(k) Insert OCTOBER

JAN

DEC) MAR

(FEB GULY
AUG
NOV

(JUNEMAY (oCT

(1) Insert SEPTEMBER


SEPT

are optimized for situations when part or


the entire tree
b) B-trees are balanced trees that
storage such as a magnetic disk. Since disk
accesses are
must be maintained in secondary
operations, a B-tree tries to minimize the number of disk
expensive (time consuming)
a variable number of keys and children. The
accesses. Each node of a b-tree may have
key has an associated child that is the root
keys are stored in non-decreasing order. Each
keys less than or equal to the key but greater than
of a subtree containing all nodes with
the preceding key. A node also has an additional
rightmost child that is the root for a
any keys in the node.
subtree containing all keys greater than

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:

5. a) Show the stages i


growth of an order-4 B-tree when the following keys are
inserted in the order given:
74 72 19 87 51 10 35 18 39 60 76 58 19 45 wBUT 2010
Answer:
74 72 19 87 51 10 35 18 39. 60 76 58 19 45
Insert 74: 74
Insert 72: 72,74

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

search (p->rc, digit) ; // rc = right child

7. What are the problems of binary tree? Explain the improvement of


performanca
by the use of height-balanced tree.
Explain how a height-balanced tree can be formed by inserting the following
elements in the given order:
1,2, 3, 4, 5, 6, 8, 9, 10, 7, 11
Show the root element the can be deleted from the above tree. WBUT
201
Answer:
1" part:
Most operations on a binary search tree (BST) take time directly proportional to the
height of he tree, so it is desirable to keep the height small. Since a binary tree with
height h contains at most 20+21t-+2h 2h+l-1 nodes, it follows that the minimum
height of a tree with n nodes is logi(n), rounded down; that is, [logan]. However, the
simplest algorithms for BST item insertion may yield a tree with height n in rather
common situations. For example, when the items are inserted in sorted key order, the tree
degenerates into a linked list with n nodes. The diffèrence in performance between the
two situatjons may be enormous: for n = 1,000,000, for example, the minimum height is
[log(n)]-19.
Self-balancing binary trees or height balanced tree solve this problem by performing
transformations on the tree (such as tree rotations) at key times, in order to keep the
height proportional to log(n). Although a certain overhead is involved, it.may be
justified in the long run by ensuring fast execution of later operations.
Maintaining the height always at its minimum value [log:(n)] is not always viable; it can
be proven that any insertion algorithm which did so would have an excessive overhead,
o
Therefore, most self-balanced BST algorithms keep the height within a constant factor
this lower bound. In the asymptotic ("Big-0") sense, a self-balancing BST structu
containingn items allows the lookup, insertion, and removal of an item in Oo8
worst-case time, and ordered enumeration of al items in O(n) time. For S
implementations these are per-operation time bounds, while for others they are amoru
bounds over a sequence of operations. These times are asymptotically optimal ano
data structures that manipulate the key only through comparisons.

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

m/2 I nonempty children.


ii) The number of keys in each internal node is one less than the number of its nonempty
children, and these keys partition the keys in the children in the fashion of a search
tree.
iv) The root has at most m children, but may have as few as 2 if it is not a leaf, or none if
the tree consists of the root alone.

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

ABCD FGHIJKLM alphabets up toP


When J has to be inserted, the nodes will be split at E and then all the
would be inserted as below

ABCD FGH KLMNOP


that they
9. Insert the following number into a binary search tree in the order
given and draw the resulting tree.
87; 36; 22; 15; 56; 85; 48; 91; 72; 6
Delete 48 and draw the resulting tree. Delete 15 and draw the tree014
resulting WBUT 2014

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

B-tree after inserting 97 Insert 61


,0082 0082

0029 0084 0097 0029 0061 0084 0097

Insert 10 Insert 45
,oo82 0020 0082

0010 0029 0061 0084 0097 0010 o046 00610084 0097

Insert 28 Insert 49
co20 OCe2
0020 0082

2010 028 0046 0O40 0061 0084 0097


0010 0028 0046 0061 0084 0097

Insert 70

0029, 0040 0082

0070 O084 0097


0010 0028 00450061
Insert 86
0082
0029 0049

0070 0084 0080 0097


0010 0028 0046 0061
Insert 68

0029 0049, 0082

00997
0010 0028 0045 0061 0088 00700084 0086

DSA-75
POPULAR PUBLICATIONS

Insert 19
0029 0043 O082

001C O0:9 00280045 co6 0068 0070 O084 08E 0097

Insert 55

0029 0061 0082

0010 0019 0028 0045 0055 0068 0070 0084 O086 0097

Insert 22
0049

0082
,0019 O020 0061

0010 0022 00280045 00550068 0070 0084 008 0087

Insert 11
0049

0081 0082
0018O023

0028 0045O055 0068 O070 0084 0080 0097


JL0022
0010 0011

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

to Question No. 5(b) of Long Answer Type Questions.


b) 1" Part: Refer

2d Part: Up to insertion of 8 12 9 1176:


Long Answer Type Questions.
Refer to Question No. 5(c) of following steps are needed.
66, 2, 1, 44 in the above tree the
Forinsertion of

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) (*)

b) The following C program does the insertion into a binary tree


* Structure */
struct bin_tree {

DSA-78
W
DATASTRUCTURE&ALGORITHM

int data;
struct bin_tree
" right, * left:

typedef struct bin_treee node;


Pinsert function/
1 void insert(node ** tree, int val) {

2 node "temp = NULL;


3 if!("tree))
4 temp (node "}malloc(sizeof{node);
temp->left = temp->right = NULL;
6 temp->data = val;
treetemp;
return;

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

a. [Line 14] Call insert() function


recursively while there is non-NULL right
ode
[Lines 3-9] When reached to rightmost node as NULL, insert new node.
b.
maximum and the minimum elements in a
12. a)Write a C function to find out the
binary search tree.
b) Given the pre-order sequence and
the post-order sequence, why cannot you
WBUT 2016]
reconstruct the tree?
Answer:
search tree nodes are defined as follows:
) Assume the binary
struct node
Btruct node *1child;
int infoD
Struct node *rchild;

DSA-79
POPULAR PUBLICATIONS

Min function -recnrsive /


struct node Min (struct node *ptr)
if (ptr--NULL)
return NULL;
else if (ptr->lchild--NULL)
return ptr:
else
return Min (ptr->lchild)
/End of min(0*7

Max function -recursive


struct node Max (struct node *pttr)
if (ptrw=NULL)
return NULL;
else if (ptr->rchild= =NULL)
return ptr;
else
return Max (ptr->rchild);
/End of max()*/

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.

13. a) What do you mean by a binary search tree? (WBUT 20177


b) Construct a binany search tree by Inserting the list of
elements one by one:
13, 10,3, 5, 18, 15, 14
c) Write an algorithm for pre-order traversal of a tree
represented by a linked-list
Answer:
a) A binary search tree is a binary tree that is either
empty or in which each node satistics
the following conditions
i) The left child has a value smaller than the parent
ii) The right child has a value greater than the
parent.

DSA-80
&ALGORITHMM
STRUCTURE
DATA

b) After inserting 13, 10, 3, 5 the tree looks like

O13

0010

0003

0005

Now, after inserting 18, 15, 14 the tree looks like

0013

0010 0018

( 0003 0015

0005 (0014

c)iC program implementation to left child


pointer
/* A binary tree node has data,
and a pointer to right child */
struct node

int data;
struct node* 1eft;
struct node* right;

*Given a binary tree, print its nodes in preorder*


Void printPreorder (struct node* node)

if (node == NULL)
return;

/* first print data of node */


printf( "8d ", node->data);

DSA-81
POPULARPUBLICATIONS

/*
then recur on left subtree */
printPreorder (node->left);
*nowrecur on right subtree */
printPreorder (node->right);

14. a) What is an AVL tree? WBUT 20177


b) Construct an AVL search tree for the data list:
AND, BEGIN, CASE, DO, END, FOR GOTO.
c) For the AVL tree you have constructed delete the following keys in the order
DO, FOR END.
Answer:
a) Refer to Question No. 17(a) of Long Answer Type Questions
b) After inserting AND and BEGIN:

(AND

(BEGIN

After inserting CASE

BEGIN

AND CASE

After inserting DO
(BEGIN

AND (CASE

DSA-82
ALGORITHM
STRUCTURE&
DATA

inserting END
After
BEGIN

AND DO

After inserting FOR

DO

2
BEGIN END

AND CASE FOR

After inserting GOTO


DO

BEGIN FOR

AND END
GOTo

) After removing DO

(CASE

BEGIN FOR

END
(Goro)
AND

DSA-83
POPULAR PUBLICATIONS

After removing FOR

CASE

(BEGIN END

AND (GOTO

After removing END


CASE

BEGIN GOTO

AND

15. a) Explaindifferent rotation mechanisms in AVL tree. WBUT 2019]


b) Show that for a non-empty binary tree, if n is the number of leaf nodes and n,
is

the number of nodes of degree 2 then n% =n, +1.


Answer:
rotations and they
a) Rotation operations are used to make a tree balanced. There are four
are classified into two types:
Single Left Rotation (LL Rotation)
In LL Rotation every node moves one position to left from the current position.
Single Right Rotation (RR Rotation)
In RR Rotation every node moves one position to right from the current position.
Left Right Rotation (LR Rotation) rotation.
The LR Rotation is combination of single left rotation followed by single right
In LR Rotation, first every node moves one position to left then one position to right
from

the current position.


Right Left Rotation (RL Rotation)
rotation.
The RL Rotation is combination of single right rotation followed by single left
In RL Rotation, first every node moves one position to right then one position to left Iron
the current position.

b) Let n be the total no. of nodes in binary tree.


no- no. of nodes of degree 01

n. no. of nodes of degree


DSA-84
ALGORITHM
DATA STRUCTURE &

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

branches in the binary tree.


n =B+ 1 .. (2)
B 0.no +|*n + 2*n2 since there would be 0 branches from no, andl branch Trom nj

nodes and two branches from n2 nodes


B n+2n2 (3)
Substituting (3) in (2).
n= ni+2n2 +1 .(4)
Equate 1

&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

b) When we delete a node, three possibilities arise.


1) Node to be deleted is leaf: Simply remove from the tree.

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.

17. Write short notes on the following:


a) AVL Tree WBUT 2013, 2015, 2018]
b) Threaded Binary Tree WBUT 2010, 2014, 2015]
c) B-tree WBUT 2012, 2013]
d) Binary Search Tree WBUT 2018]
Answer:
a) AVL Tree:
An AVL Tree is a form of binary tree, however unlike a binary tree, the worst case
scenario for a search is O (log n). The AVL data structure achieves this property by
placing restrictions on the difference in height between the sub-trees of a given node, and
re-balancing the tree if it violates these restrictions.
The complexity of an AVL Tree comes from the balance requirements it enforces on each
node. A node is only allowed to possess one of three possible states (or balance factors
Left-High (balance factor-1)
The left-sub tree is one level taller than the right-sub tree
Balanced (balance factor 0)
The left and right sub-trees are both the same heights
Right-High (balance factor +1)
The right sub-tree is one level taller than the left-sub tree.
If the balance of a node becomes -2 (it was left high and a level was lost from ic
the

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

b) Threaded Binary Tree:


Refer to Question No. 3(a) of Long Answer Type Questions.
c) B-trece:
Definition: A B-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
m/2 Inonempty children.
ii) The number of keys in each internal node is one less than the number of its nonempty
children, and these keys partition the keys in the children in the fashion of a search
tree.
iv) The root has at most m children, but may have as few as 2 if it is not a leaf, or none if
the tree consists of the root alone.
There are some disadvantages also
The nodes of a B-tree do not normally contain the same number of value entries.
They normally do containa certain amount of free space.
Difficulty in traversing the keys sequentially.
Note: B-tree is not a binary tree. A B-tree is also known as the balanced sort tree.

d) Binary Search Tree:


Refer to Question No. 13(a) & (b) of Long Answer Type Questions.

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.

Multiple Choice Type Questions


removal of which makes a graph disconnected is called [WBUT 20071
1.The vertex,
b) bridge
a) Pendant vertex
d) colored vertex
c) articulation point
Answer: (C)
in a dtrected graph is called WBUT 2007, 2018]
2. Avertex of in-degree zero
b) sink
a) articulation point d) root vertex
c) isolated vertex
Answer: (c)
digraph is WBUT 2007, 2012, 2016]
3. Adjacency matrix of a
b) symmetric
a) identity d) none of these
t) asymmetric
Answer: (b)
DSA-88
4. Which
DATASTRUCTURE & ALGORITHM
data structure is
a) Stack used for breadth
c) Both stack first traversal of a graph? [WBUT Z000
and queue b) Queue
Answer: (6) d) None of these
5. The adjacency
a) Unit matrixmatrix of an undirected
graph is WBUT 2008, 2010]
c) Symmetric
matrix b)
Asymmetric matrix
Answer: (c) d) None of these

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

10. BFS constructs


a) a minimal cost spanning tree of a graph WBUT 2010, 2014, 20181
b) a depth first spanning tree of a graph
c) a breath first spanning tree of a graph
d) none of these
Answer: (a)

11. A
complete directed graph of 6 nodes has..
S....*****s* WBUT 2011]
a)5 b) 10 c) 20
Answer: (b) d) 25

12. Avertex with degree one in a graph ls called WBUT 2012]


a) leaf b) pendant vertex c)end vertex d) none of these
Answer: (b)
DSA-89
POPULAR PUBLICATIONS

used? WBUT 2013]


13. To implement DFS which data structure is generally
(a) & (b) d) None of these
a) b) Queue c) Both
Stack
Answer: (a)
WBUT 2014
14. Adjacency matrix for a digraph is- symmetric matrix
b)
a) unit matrix
d) none of these
c) asymmetric matrix
Answer: (6)
following graph?
15. What is the sum of the degrees of all the vertices in the WBUT 2017
a) 19
b) 20
c) 5
none of these
d)
Answer: (a)
WBUT 2017
16. The adjacency matrix of an undirected graph
b)
is
Asymmetric matrix
a) Unit matrix
d) none of these
c) Symmetric matrix
Answer: (C)
WBUT 20171
17. A path is
a) a closed walk with no vertex repetition
b) an open walk with no vertex repetition
c) an open walk with no edge repetition
d) a closed walk with no edge repetition
Answer: (C).

Short Answer Type Questións


Describe Kruskal's minimal spanning tree algorithm. WBUT 2008, 2018]
1.
Answer: spanning tree
Kruskal's algorithm is an algorithm in graph theory that finds a minimum
that forms a
for a connected weighted graph. This means it finds a subset of the edges
in the tree is
tree that includes every vertex, where the total weight of all the edges (a
minimized. If the graph is not connected, then it finds a minimum spanning forest an
is
minimum spanning tree for each connected component). Kruskal's algorithm
example of a greedy algorithm.
It works as follows:
create a forest F(a set of trees), where each vertex in the graph is a separate tree
create a set S containing all the edges in the graph
while S is nonempty
remove an edge with minimum weight from S

DSA-90
DATA STRUCTURE & ALGORITHM

if that edge connects two different trees, then add it


to the forest, combining two trees
into a single tree
. Otherwise discard that edge.
At the termination of the algorithm,
the forest has only one component and forms a
minimum spanning tree of the graph.

2. What is a minimum spanning tree? Describe Huffman's


Algorithm. WBUT 2012]
Answer:
1" Part:
A Minimum Spanning Tree in an undirected connected weighted
graph is a spanning tree
of minimum weight (among all spanning
trees). The minimum spanning tree may not be
unique. However, if the weights of all the edges
are pairwise distinct, it is indeed unique.
The following figures show a weighted graph and its minimum
spanning tree.

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

3.What is the adjacency matrix representation of a graph WBUT 2013]


Answer:
The adjacency matrix
of a graph is

0 0
0

4. Write the Prim's algorithm for


finding MST from a graph. WBUT 2014, 2016]
Answer:
Prim's algorithm is a Greedy algorithm. It starts with an empty spanning tree.
to maintain two sets of vertices. The first
The idea is
set contains the vertices already included in the
MST, the other set contains the vertices not yet included. At every
step, it considers all
the edges that connect the two sets, and picks the minimum
weight edge from these
edges. After picking the edge, it moves the other endpoint
of the edge to the set
containing MST.
Algorithm
1) Createa set mstSet that keeps track of vertices already
included in MST.
2) Assign a key value to all vertices in the input
graph. Initialize all key values as
INFINITE. Assign key value as 0 for the first vertex so that it is
picked first.
3) While mstSet doesn't include all vertices
....a) Pick a vertex u which is not there in mstSet and has minimum key
value.
....b) Include u to mstSet.
....c) Update key value of all adjacent vertices of u. To update
through all adjacent vertices. For every adjacent vertex v, the key values, iterate
if weight of edge u-v is less
than the previous key value of v, update the key value as weight
of u-v
5. For the following graph find the BFS and DFS traversal
with proper algorithm.
WBUT 2015]

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

| Step 1 -> Node A


| Step 2 ->Node B
Step 3-> Node C
Step 4-> Node F
| Step 5-> Node G
Step 6-> Node D
Step 7-> Node E

The steps involved in depth first traversal are as follows:


----*-=

Step 1-> Node A


Step 2-> Node B
Step 3-> Node C
Step 4 -> Node F
|

| Step 5 -> Node D


Step 6-> Node G
Step 7-> Node E

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.

LLong Answer Type Questlons


1.
Compare BFS and DFS. Discuss the two different ways of representing a
a)
graph. wBUT 2009]

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

For directed graphs


A[i. j]= 1. if there is an edge directed i &j
A [i.
j) = 0, otherwise
Adjacency Matrir
2 3 4

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.

i) Adjacency List: It is a linked listrepresentation of a graph where each vertex


represents a head node. Each head node has a list associated with
it which
represents the edges. The nodes of the list form a path between the head node and
all other reachable vertices in the graph from that head node.

DSA-97
POPULARPUBLICATIONS

Head nodes

Example

Undirected Graph

Head nodees
V,

MLMI

Directed graph

Drawbacks: When a graph is large, it is necessary to handle to many numbers of


pointers, which can be complex.

iii) Adjacency Multilist: From the adjacency list representation


of an undirected
graph, it is clear that each edge (Vi, Vj) is represented by
two entries, one is list Vi
and another is list Vj. This is unnecessary wastage
of the memory as the
information present is same at both the nodes (1,2)= (2,1).
To avoid this, the adjacency multilist is used. Using this
representation, the nodes are
shared amongst the several lists.
In this method for each edge of the graph, there will
be exactly one node. But this node
will provide the information about two more nodes to
which it is incident.
The node structure with this representation will be:

m-tagfield
m L V V L PL
V1, V2Vertex
P1, Pp-- Incident paths

DSA-98
ALGORITHM
DATASTRUCTURE &

field that is used to indicate whether or not the edge has


been
m is a
one bit mark
examined.

Consider the following graph.

Totaldistinct edges are:


{Vi, V2, Vi, V3j. {V1, Va, {v2. Va}. {v2, va}, {vs, v»}, {v3,
Vs} & {va. Vs}. All other

edges represent the same information, because this is an undirected graph.


The adjacency multilist representation is as follows

V2
N N|N
N NI

V3
V N2

V4
NILN N3

S
N N4

NILNLN N5

The lists are: N6


Vertex 1
: NI» N2» N3
Vertex
Vertex
2: NI N4NS
3: N4 N6N7
N2
>
NILN NIL
N7

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

c) What is Complete Graph? WBUT


Show that the sum of degree of all 2009)
the vertices in a graph is always even.
WBUT
OR,
2009
Show that the number of vertices of
odd degree in a finite graph is even.
WBUT 2017
OR,
Prove that the number of odd degree vertices in a graph is always even.
BUT2018)
Answer:
1" Part: A graph is said to be complete if there exist an edge between every
pair of
vertices.

2 Part: The number of odd degree vertices in a graph is always even:


Degree of a vertex is defined as no. of edges incident on a particular vertex with the
self
loop counted twice. Now, let us take the sum of degree of all the vertices. Now, this
summation is an even number, because each edge contributes twice when we are
calculate degree of different vertices. Now, if we take the summation of all the degrees
that is nothing but the twice the number of edgesd(y) = 2e »even number
f=l

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,

selected node). In the image,


also have a current node. Initially, we set to (our
it C
We'll
we mark the current node with a red
dot.
Now, we check the neighbours of our
current node (A, B and D) in no specific order
Let's begin with B. We add the minimum
distance of the current node (in this case, 0)
with the weight of the edge that connects our current
node with B (in this case, 7), and we
7. We compare that value with the minimum
distance of B (infinity); the
obtain 0 + 7
lowest value is the one that remains as the
minimum distance of B (in this case,7 is less
than infinity):

C, our current node)


Now, let'scheck neighbour A. We add 0 (the minimum distance of
with (the weight of the edge connecting our current node
I with A) to obtain 1. We
Compare that with the minimum distance of A (infinity), and leave the
1 smallest value:

DSA-101
POPULARPUBLICATIONS

OK. Repeat the same procedure for D:

We have checked all the neighbours


of C. Because of that, we mark it as visited.
represent visited hodes with a green check mark: Ie

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.

than E's minimum


distance (9), so we
need to check E. 4 +1 = 5, which is less
We only current node.
Then, we mark B as visited and set E as the
leave the 5.

anything. We mark
non-visited neighbours, so we dont need to check
E doesn't have any
it as visited.

we are done! The minimum distance of each node now


As there are not univisited nodes,
actually represents the minimum
distance from that node to node C.

DSA-103
POPULARPUBLICATIONS

4. Write short notes on the following:


a) BFS vs DFS
BFS WBUT 2010]
c) Dijkstra's Algorithm WBUT 2012]
d) DFS in graph WBUT 2013)
WBUT 2014,
Answer: 2018
a) BFS vs. DFS: Refer to Question No. 1(a)
of Long Answer Type Questions.
b) BFS: Refer to Question No. 1(a) of Long Answer Type Questions.
c) Dijkstra's Algorithm:
Dijkstra's algorithm works on the principle that
the shortest possible path from the source
has to come from one of the shortest paths already discovered. A
way to think about this
is the "explorer" model--starting
from the source, we can send out explorers
travelling at a constant speed and crossing each edge in time proportional to cach
the weight of
the edge being traversed. Whenever an explorer reaches a vertex,
it checks to see if it was
the first visitor to that vertex: if so, it marks down the path it took to
get to that vertex
This explorer must have taken the shortest path possible to reach
the vertex. Then it sends
out explorers along each edge connecting the vertex to its neighbors.
It is useful for each vertex of the graph
to store a "prev" pointer that stores the vertice
from which the "explorer" came from. This is the vertex that directly
precedes the current
vertex on the path from the source to the current vertex.
The pseudocode for Dijkstra's algorithm is fairly simple and reveals a bit more about
what extra information needs to be maintained. Vertices will be numbered starting
from 0
to simplify the pseudocode.
Given a graph, G, with edges E of the form (vl, v2) and vertices
V, and a
source vertex, s
dist: array of distances from the source to
prev: array of pointers to preceding
each vertex
verticess
i :Loop index
F :list of finished vertices
U list or heap unfinished vertices

/*
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 &

heap construction the elements from the root ar


or min-heap respectively. After the
heap
is reconstructed. This
process continues une
taken out irom the tree and the heap structure
the heap is empty.

Multiple Choice Type Questions


called the
1. The ratio of the number of items in a hash table, to the table size is 2009, 2016]
[WBUT 2007,
d) all of these
load factor
a) b) item factor c) balanced factor
Answer: (a)

Which of the following is nota requirement of good hashing function?


b) Reduce the storage space
2.
a) Avoid collision 2008, 2015]
c) Make faster retrieval d) None of these WBUT
Answer: (6)
WBUT 2007
Stability of Sorting Algorithm is important for
3.
a) Sorting records on the basis of multiple keys
b) Worst case performance of sorting algorithm
Sorting alpha numeric keys as they are likely to be the
same
d) None of these
Answer: (a)
WBUT 2007]
Which of the following is the best time for an algorithm?
4.
d) Ofn log2 n)
a) O(n) b) O(log2 n) c) O(2n)
Answer: (6)

5. The Linear Probing Technique for collision resolution can


lead to [WBUT 2009
a) Primary clustering
b) Secondary clustering
c) Overflow d) Efficiency storage utilization
Answer: (a)
array is WBUT 2009]
6. The fastest sorting algorithm for an almost already sorted
a) quick sort b) merge sort c) selection sort d)insertion sort
Answer: (d)

The time complexity of binary search is


7. WBUT 2009]
a) O(n) b) O(n) c) Oflog n) d) O(n logn)
Answer: (c)

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

9. Which of the following sorting


procedures is the slowest? WBUT
a) Quick sort b) Heap sort 2010
c) Merge sort d) Bubble sort
Answer: (d)

10. Which of the following traversal


techniques lists the elements of a
search tree in ascending order? binan.
WBUT 2011,
a) pre-order b) Post-order 2015)
c)Inorder d) None of these
Answer: (c)

11. Binary search cannot be used in linked lists. [WBUT 2011]


a) True b) False
Answer: (6)

12. Breadth-first-search algorithm


a) stack
uses..data structure WBUT 20111
b) queue c) binary tree d) none of these
Answer: (6)

13. The best case complexity of insertion sort is- WBUT 2011
a) o(r') b) o(nlog,n) d) O(n)
Answer: (d)

14. Which of the following is no related to hashing?


a) Synonyms
WBUT 2011]
b) Collision c) Balance d) Load factor
Answer: (c)

15. A machine needs a minimum of 100sec to sort 1000 names by quick


sort. The
minimum time needed to sort 100 names will be approximately WBUT 2012]
a) 72.7 sec b) 11.2 sec c) 50.2 sec d) 6.7 sec
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)

18. Which of the following is a hash function? WBUT 2014


a) Quadratic probing b) chaining
c) open addressing d) folding
Answer: (a)

DSA-108
ALGORITHM
STRUCTURE&
DATA

8, 22, 7, 3, °"RUT 2014]


19.The number of swapping needed to sort numbers WBU
ascending order using bubble sort is d) 14
a) 11 b) 12 c) 13
Answer: (d)
WBUT 2014]
20. Binary search uses
and conquer strategY
a) divide and reduce strategy b) divide
c) heuristic search d) both (a) and (b)
Answer: (b)
WBUT 2015]
21. Merge sort uses b'backtracking approach
a) divide and conquer strategy
c) heuristic search
d) greedy approach
Answer: (a)
[WBUT 2017, 2019]
22. The prerequisite condition of Binary
search is array
b) ascending order
a) unsorted array d) sorted array
c) descending order array
Answer: (d)
n elements is
complexity of binary search for a list having WBUT 2019]
23. The worst case
d) n 2
b) n log 2" c)n
a) log 2"
Answer: (b)
time
to be stored. What is the worst case 2019]
24. Consider that n
elements are WBUT
O(n^2)
complexity of Bubble sort? c) O(n)
d)
b) O(log 2n)
a) 0(1)
Answer: (d)
WBUT 2019]
performance of Selection sort algorithm?
25. What is the
worst case c) 0(n)
d) O(n log n)
b) O(n'n)
a) o(log n)
Answer: (b)
element with
relatively passes through a list to exchange the firstcalled
26. A sort which
it and then repeats with a new first element is [WBUT 2019]
any element less than
c) heap sort d) quick sort
b) selection sort
a) insertion sort
Answer: (a)

Short Answer Type Questions

of binary search over sequential search.


1. Explain the advantages WBUT 2007, 2013]

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).

2. What is hashing? WBUT 2007, 2012, 2014, 2017]


OR,
Define Hashing. [WBUT 2015]
What is collision? WBUT 2017]
Explain Linear Probing & Quadratic Probing with example. [WBUT 2007]
OR,
Define 'Hashing. Explain with a suitable example the collision resolution scheme
using linear probing with open addressing. WBUT 2010]
OR,
Define Hashing. Explain one collision resolution scheme citing one example.
WBUT 2013]
OR,
Write two hash functions WBUT 20171
OR,
Explain with suitable example the collision resolution scheme using linear probing
with open addressing [WBUT 2019]
Answer:
1 Part:
Hashing is a method for storing and retrieving records from a database. It lets you insert,
delete, and search for records based on a search key value. When properly implemented,
these operations can be performed in constant time. In fact, a properly tuned hash system
typically looks at only one or two records for each search, insert, or delete operation. This
is far better than the O(log n) average cost required to do a binary search on a sorted array
of n records, or the Olog n) average cost required to do an operation on a binary search
tree. However, even though hashing is based on a very simple idea, it is surprisingly
difficult to implement properly. Designers need to pay careful attention to alt of the
details involved with implementing a hash system.
A hash system stores records in an array called a hash table, which we will call HT
Hashing works by performing a computation on a search key K ina way that is intended
to identify the posítion in HT that contains the record with key K. The function that does

DSA-110
ALGORITHMM
DATASTRUCTURE &

by the letter h. >lnce


thiscalculation is called the hash function, and is usually denoted
satisfies the needs of tne
hashing schemes place records in the table in whatever order
in the hash table is also
address calculation, records are not ordered by value. A position M
be denoted by the variable
known as a slot. The number of slots in hash table HT will
with slots numbered from 0 to M- 1.

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

flag = 1; //set flag = 1if the element is found


break;

else if (item <A[mid])


right =. mid 1; /* Compute new right from the right sub array */
else
left = mid + 1; /* compute new left from the left sub array */
return flag;

5. "Binary search technique cannot be implemented using Linked


the validity of the
list." Justify
statement. [WBUT 2009]
Answer:
he statement is not true as it can Binary Search can be implemented using Linked List-
however it would be less efficient than array.
Binary search on an array so fast and efficient because of its the ability
to access any
element in the array in constant time. Thus one can get to the middle of the array
just by
saying array[middle].
DSA-113
POPULAR PUBLICATIONS

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

Sorted Array: 3.2, 0,


Tree nodes: 9, 10, 11, 12 Sorted Array: 7, 3,2,0,-5
Tree node: 10, 11, 12 Sorted Array: 9,7, 3,2, 0, -5
Tree nodes: 11, 12 Sorted Array: 10,9, 7, 3,2, 0, -5
Tree nodes: 12 Sorted Array: 11, 10, 9,7, 3,2, 0, -5
Tree nodes: Sorted Array: 12, 11, 10,9,7, 3,2, 0,-5
2nd
Part:
If the first few objects are already sorted, an unsorted object can be inserted in the sorted
set in proper place. This is called insertion sort. An algorithm consider the elements one
at a time, inserting each in its suitable place among those already considered (keeping
them sorted). Insertion sort is an example of an incremental algorithm; it builds the
sorted sequence one number ata time.

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

void buildheap (int [1. int);


void heapsort (int [1, int);
int main (void)
10, 7, 17, 6};
heapArr [N] = {15, 19,
int
int i;
printf ("\nBefore Sorting: \n")
for (i = 0; i < N; i++)
printf( "8d\t", heapArr [i]);
buildheap (heapArr, N);
heapsort (heapArr, N) ;:
Sorting: \n");
printt(" \nAfter
for (i = 0; i < N; i++)
printf("8d\E", heapArr [i]) ;

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;

8.Deduce the average


Answer: time complexity
of Quicksort algorithm.
The basic idea of Quicksort WBUT 2015]
1. Pick one element is as given below:
2. Make one pass
in the array, which will
through the be th pivot.
Sothat: array, called a partition step,
re-arranging the entries
the pivot is in its proper
place.
entries smaller than the pivot
entries larger than the pivot are to the left of the pivot.
3. Recursively apPply are to its right.
quicksort to the part of the array
and to the right part of the array. that is to the left of the pivot,
Analysis
TON) = T(i) + T(N i
-1)+ cN -

The time to sort the file is equal to


o the time to sort the left partition with i elements, plus
o the time to sort the right partition with N-i-1 elements,
plus
o the time to build the partitions

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)

T(2y3 T(1)/2 +2c/3


Add the equations and cross equal terms
T(NYN+1) = T(1/2 +2c S (1/j), = 3
T(N) = (N+1X1/2 +2c S(1/j))
j to N+l
The sum S (1/5), j =3 to N-1, is about LogN
Thus T(N) = O(NlogN)

9.What is the primary criterion of performing binary search technique on list of


data? a
WBUT 2015]
Answer:
A binary search algorithm is one method of efficiently processing a sorted list to
determine rows that match a given value of the sorted criteria. It does so by "cutting" the
set of data in half (thus the term binary) repeatedly, with each iteration comparing the
Supplied value with the value where the cut was made. If the supplied value is greater
than the value at the cut, the lower half of the data set is ignored, thus eliminating the
need to compare those values. The reverse happens when the skipped to value is less than
the supplied search criteria. This comparison repeats until there are no more values to
compare.
The binary search algorithm was able to eliminate the need to do a comparison on each of
the records, and in doing so reduced the overall computational complexity of our request
for the database server. Using the smaller set of sorted weight data, we are able to avoid
needing to load all the record data into memory in order to compare the product weights
to our search criteria.

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 &

Part: the data exhibIts som


The prime numbers are used to minimize collisions when
particular partem. The reason prime numbers are used to neutralize the
effect or paet
in the keys in the distribution of collisions of a hash function.

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) {

mid = left + (right-left) /2; 11same as(left


right) / 2
if (arr [mid)==target) (
return mid;

if (arr [mid) < target)


left = mid + 1;

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).

Step 1: 12, 32, 23, 15, 34, 11, 25


Step 2: 12 32, 23, 15, 34, 11,25 (Compare)
Step3: 12,32,
23, 15, 34, 11, 25 (Compare)
Step 4: 12, 23,32, 15, 34, 11, 25 (Swap)
Step 5: 12, 23, 32,15, 34, 11, 25 (Compare)
Step 6:12, 23, 15.32, 34, 11, 25 (Compare)
8tep 7:12, 23, 15, 32,34, 11, 25 (Compare)
Step 8:12, 23, 15, 32, 34, 11, 25 (Compare)
Step 9:12, 23; 15, 32, 11, 34, 25 (Swap)
Step 10: 12, 23, 15, 32, 11, 34,25 (Compare)

DSA-119
POPULAR PUBLICATIONS

Step 12, 23, 15, 32, 11. 25, 34 (Swap)


11:
Step 12, 23. 15, 32, 11, 25, 34 (compare)
12:
Step 12, 23, 15. 32, 11, 25, 34 (compare)
13:
Step 12, 15, 23. 32, 11, 25, 34 (Swap)
14:
Step 15:
12, 15, 23.32. 11, 25, 34 (compare)
12, 15, 23, 32, 11, 25. 34 (compare)
Step 16:
Step 17:
12, 15, 23, 11.32, 25, 34 (Swap)
Step 18:
12, 15, 23. 11, 32, 25, 34 (compare)
12, 15, 23, 11, 25. 32, 34 (Swap)
Step 19:
Step 20: 12, 15, 23, 11, 25, 32, 34 (compare)
Step 21: 12, 15, 23, 11, 32,25, 34 (compare)
Step 22: 12, 15, 23, 11, 32, 25, 34 (compare)
Step 21: 12, 15, 23, 11, 32, 25, 34 (compare)
Step 22: 12, 15, 11,23, 32, 25, 34 (Swap)
Step 23: 12, 15, 11, 23, 32, 25, 34 (compare)
Step 23: 12, 15, 11, 23, 32, 25, 34 (compare)
Step 23: 12, 15, 11, 23, 32, 25, 34 (compare)
Step 23: 12, 11, 15, 23, 32, 25, 34 (Swap)
Step 23: 12, 11. 15, 23, 32, 25, 34 (Compare)
Step 23: 11, 12, 15, 23, 32, 25, 34 (Swap)
Done.

Long Answer Type Questions


WBUT 2007]
example the Merge sort algorithm.
1. a) Explain with an WBUT 20071
Merge sort.
b) Write an algorithm for OR,
example. WBUT 2013]
merge sort with an
Show the operation of complexity of selection sort and insertion sort. 2007]
c) Compare the best case time [WBUT

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

b)/*Recursive Merge Sort algorithm*/


mergesort (int all, int low, int high)

int mid;
if (1owehigh)

mid= (1ow+high) /2;


mergesort (a, low, mid);
mergesort (a, mid+1, high);
merge (a, low, high, mid);

return(0);
/* Merge function*/
merge (int all, int low, int high, int mid)

int i, j, k, cl501;/* assume size of array is 50*


i=low;
j=mid+1;
k=low;
while( (i<=mid) && (j«=high))

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++

for (i=low; i<k; i++)

ali]=c[il:
DSA-121
POPULARPUBLICATIONS

Let the original unsorted array is: 84525


In the first step it gets split into
84 5 2 5 ( denotes the divider)
Further splitting and merging is shown in the next steps:
8 l 4 I 5 25 (split)
8 4 # 5 2 5 (can't split, merges a single-element array and returms)
8 4 5 25 (can't split, merges a single-clement array and returns)
f
48 5 2 5 (merges the two segments into the array)
4 8 5 | 25 (split)
48 5 25 (can't split, merges a single-element array and returns)
4 8 5 2 ||| 5 (split)
4 8 5 I1 2 | 5 (can't split, merges a single-clement array and returns)
4 8 5 || 2 || 5 (can't split, merges a single-element array and returns)
4 8 125 (merges the two segments into the array)
5
4 8 2 5 5 (merges the two segments into the array)
24558(merges the two segments into the array)

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).

2. a) Explain with a suitable example, the principle of operation of Quiek eort


WBUT 2007, 2009, 2010
Answer:
In Quick-Sort we divide the array into two halves. We select a pivot
element (normally
a sorting in such a manner that all the
the middle elementof the array), & perform
right is
elements to the left of the pivot element is lesser than it & all the elements to it's
arrays. Then we recursively call the
greater than the pivot element. Thus we get two sub
sorting.
quick sort function on these two sub arrays to perform the necessary
Let us consider the following unsorted array:
a[] = 45 26 77 14 68 61 97 39 99 90
Step 1:
z 9. We find the pivot element by the formula
We choose two indices as left = 0 and right
So the pivot element is a [141 68. We also start
aleft + right] /2 = a [0 +9J/2 =a [4).
with a [left] = a 10] =45 and a fright) a [9] 90
= =

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.

b)Find the complexity of Quick sort algorithm.


WBUT 2007, 2013]
Answer:
Refer to Question No. 8 of Short Answer Type Questions.

3. a) Why is hashing referred as a heuristic search method? WBUT 2008]


Answer:
A heuristic algorithm, is an algorithm that is able to produce an
acceptable solution to a
problem in many practicàl scenarios, in the fashion of a general heuristic, but
for which
there is no formal proof of its correctness. Alternatively, it may be
correct, but may not
be proven to produce an optimal solution, or to use reasonable
resources. Heuristics are
typically used when there is no known method to find an optimal solution, under
the
given constraints (of time, space etc.) or at all. It is a technique whereby or items
are
placed into a structure based on a key to-address transformation.
We use Hashing for

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.

D) What is the primary advantage of hashing over deterministic search algorithms?


WBUT 2008]
Answer:
in deterministic search method we try to explore all the data items sequentially, one by
Oonewhich gives different polynomial time complexity. But
hashing is the searching
hethod where the searching time is always O(1). this sense later is always
s
advantageous.

DSA-123
POPULARPUBLICATIONS

C)Define collision. Discuss two collision


resolution techniques and compare their
performances. WBUT 2008]
OR,
Discuss different collision resolution techniques. WBUT 2015, 2017]
Answer:
A COlision between two keys K & K' occurs when both have to be stored in the table &
both hash to the same address in the table.
The two collision resolution techniques are:
Open addressing: It is a general collision resolution scheme for a hash table. In case
oT 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 include:
a) Linear Probing (Sequential Probing)
b) Quadratic Probing
c) Double Hashing (Re Hashing)
Chaining: It is a collision resolution scheme to avoid collisions in a hash table by
making use of an external data structure. A linked.list is often used.

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)
-

H (9)=2 (Using Division Remainder Method)


2, which is 58 in our example. But
Now here, already there is one element in the position
58 in our example. When this kind of
9 is also hashed to position 2, which is occupied by
place.
situation occurs we say that a collision has taken
an adjacency list representation. Whenever a
The collision avoided by chaining meth0d is
where
collision takes place we just add to the adjacency list to the corresponding header
the collision occurred.
In our example collision occurred
at header node 2. So we just add 9 and 58 to it as an
occurs at 2 we add it to our existing list.
adjacency list. If any further collision

DSA-124
&ALGORITHM
DATASIRUCTURE

integer value for searching


a data. Inis
hash tabie uses hash functions to compute an
giving us a constant une
A
can then be used as an index into an array,
integer value
chaining, we cannot always
complexity to find the requested data. However, using
the hash table is very small or the
hasn
achieve the average time complexity of O (1).If array.
to build in one index in the
function is not good enough then the elements can start
linked list associated to that index.
And hence all n elements could end up in the same
is equivalent to looking up a data
Therefore, to do a search in such a data arrangement
to be O (n) time.
element in a linked list, something we already know
WBUT 2008]
d) Why the hash functions need to be simple?
Answer:
The reason is that, the computation itself will
consume less amount of time.

where you will prefer


4.What do you mean by hashing? What are the applications
you mean by collision? How is it
hash tables to other data structures? What do WBUT 2011]
handled?
Answer:
Hashing is a method for storing and retrieving records
from a database. It lets you insert,
delete, and search for records based on a search key value. When
properly implemented,
In fact, a properly tuned hash system
these operations can be performed in constant time.
typically looks at only one or two records for each search,
insert, or delete operation. This
is far better than the O(log n) average cost required to do a binary
search on a sorted array
to do an operation on a binary search
of n records, or the O(log n) average cost required
tree. However, even though hashing is based on
a very simple idea, it is surprisingly
difficult to implement properly. Designers need to pay careful attention to
all of the
details involved with implementing a hash system.
A hash system stores records in an array called a hash table (HT). Hashing works by
pertorming a computation on a search key K in a way that is tended to identify the
i

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 (alj] < min)

min =" a [il;


loc = ji

if (loc ! = i)

temp = a[il;
a[i] = a[loc];
a[loc] = temp

printf("\nThe sorted array


for (i = it+)0; i < n;
is: \n")
printf(83d", al[il);

Time Complexity of Selection Sort


For first pass the inner for loop iterates n 1 times. For sécond pass
the inner for loop
-

terates n 2 times and so on. Hence the time complexity


-
of selection sort is
(n-1)+(n-2)+(n-3)+... t2 +1
[(n-1)*(n-1+1)}/2
(n(n-1)]/2
0 (n^)
The selection sort minimizes the number of swaps. Swapping
data items is time
consuming compared with comparing them. This
the amount
sorting technique might be useful when
of data is small.
.a) In which cases, QuickSort becomee 'Slowert'? Wat ie the remedy lin
cases? those
Compare the performance and operation of
ubblesort and SokkettonSort.
UT 2009] DSA-127
POPULAR PuBLICATIONS

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

b) The basic idea of Bubble Sort is to: and an un-sorted


Data elements are grouped into two sections: a sorted section
section.
section and re-arrange its position with its
Go through every element in the un-sorted higher position. At the end, the
neighbour to put the element with higher order on the
the un-sorted section, and moved to
element with the highest order will be on top of
the bottom of the sorted section.
un-sorted section.
B. Repeat step 2 until no more elements left in the
Performance: Best Case: O(n), Worst Case: O(n*)
The basic idea of Selection Sort:
sections: a sorted section and an un-sorted
1. Data elements are grouped into two
section. high, find the element with the lowest
2. Assuming the sorting order is from low to
comparable order from the un-sorted section. section.
sorted
Place the found element to the end of the
4. Repeat step 2 and 3 until no more
elements left in the un-sorted section.
Performance: Best Case: O(n), Worst Case: O(n)
Why does it run faster than bubble
sort in
7. Explain the merge sort algorithm. array
merge sort algorithm will sort the following
most of the cases? Show how the
in increasing order:
100, 90, 80, 70, 60, 50, 40, 30, 20 WBUT 2011
Analyze the time complexity of the merge sort algorith
Answer: divide and conquer strategy. First, the sequence to
is based on a
The Mergesort algorithm independently
decomposed into two halves (Divide). Each half is sorted
be sorted is to a sorted sequence (Combine)
as
two. sorted halves are merged
(Conguer). Then the
shown in Figure below. hi.
following procedure mergesort sorts a sequence a from index lo to index
The
hi )

void mergesort (int lo, int


if (lo<hi)

int m=(lo+hi) /2
mergesort (l0, m);
mergesort (m+ 1, hi);
merge(lo, m, hi);|

DSA-128
DATA STRUCTURE & ALGORITHM

index m in the middle between lo and


First,
sequence (from lo to m) and the
hi is determined. Then the first part o
second part (from m+1 to hi) are sorted by recursive cais
of mergesort. 1hen the two sorted halves are merged by
procedure merge. KCoubio
ends when lo = hi, 1.e. when a subsequence
consists of only one element.
The main work of the Mergesort algorithm
is performed by function merge. Funetion
merge is usually implemented in the following
way: The two halves are first copied into
an auxiliary array b. Then the two halves
are scanned by pointers i and j and the
respective next-greatest element at each
time is copied back to array a.
void merge (int lo, int m, int hi)
int i, i, k;

// copY both halves of a to auxiliary array b


for (i=lo; i<=hi; i++)
b[i]=a[il;
i=l0; j=m+1; k=l0;
copy back next-greatest element at each time
while (i<=m && j<=hi)
if (b[i]<=blj1)
a [k++]=b[i++];
else
a [k++]=b[j++]:
1 copy back remaining elements of first half (if any)
while (i<=m)
a [k++]=b[i++1;
MergeSort has the average case time of O(nilog(n)). Moreover, Mergesort is a stable sort,
and there is no worst-case scenario. Bubble sort as the average and worst case complexity
as O(n). Hence MergeSort is better than Bubble sort in most of the cases.
Sorting of array 100, 90, 80, 70, 60, 50, 40, 30, 20

Step 1: the array is divided into 2 parts recursively


100, 90, 80, 70 , 50, 40, 30, 20

100,90 80,70 60,50 40, 30,20

100 90 80 70 60 50 40 30,20

100 90 80 70 60 50 40 30 20

DSA-129
POPULARPUBLICATIONS

Step 2: the arrays are now merged


100 90 80 70 60 50 40 20,30

90,100 70, 80 50, 60 20,30,40

70,80,90,100 20,30,40,50, 60,

20,30,40,50,60,70,80,90,100 final sorted array

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

INPUT T" pass 2d pass 3r" pass (sorted)


839 097 189 674
562 189 192 939
674 939 097 986
2nd
Part:
Suppose we nave a list of n records
generalize the problem a little
each with a key that's a number from | to K (WE
so k is not necessarily equal to n)
We can soIve this by making
an array of linked lists. We move each input
list in the appropriate position record into tne
of the array then concatenate all the lists
bucket sort(L) together in order.

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

for (i = 0; i <= k; i++)


concatenate Y [ij onto end of L

What to do when k is large? Think about


the decimal representation of a number
x = a + 10 b * 100 c+
1000 d+..
where a,b,c etc all in range 0..9. These digits
are easily small enough to do bucket sort.
radix sort (L):
bucket sort by a
bucket sort byb
bucket sort by c

or more simply
radix sort (L)

while (some key is nonzero)

bucket sort (keys mod 10)


keys = keys 10

Inradix sorting, the last pass of bucket sorting is the one


with the most effect on the
Overall order. So
we want it to be the one using the most important digits. The previous
Ducket sorting passes are used only to
take care of the case in which two items have the
Same key
(mod 10) on the last pass.

DSA-131
POPULAR PUBLICATIONS

b) The time complerity of Binary Search is as follows:


In each iteration, the array is split into two halves. Thereby we can say that the binary
search takes the form ofa binary tree. The time complexity is thus O(loga n) in worst case
also.

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.

Algorithm: INTERPOLATON SEARCH


/*
Given: x, and a <... a
Return: i such that x =a
0 if no such i exists **
i=l
n
LO:=a
HI:
ifx <LO then return 0
ifx2 HI then i :=j LO and x sHI
loopinvariant: x2
while (i<j) do
m: floor(i+G-i)"(x-LO) / (HI-LO))
MID:am
if (x> MID) then
im+l1
LO MID
else if (x <MID) then
j#m-1
HI := MID
else
DSA-132
&ALGORITHM
DATA STRUCTURE

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

in best, average as well as in worst case also). A drawback of mergesort is


is O(nlog.n)

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
=

m. Works badly for many types of patterns in the input data.


Knuth Variant on Division h(k)=k(k+3) mod m. Supposedly works much better than the
raw division method.
Multiplication Method (Cormen). Choose m to be a power of 2. Let A be some random-
-
looking real number. Knuth suggests M = 0.5*(sqrt(5) 1). Then do the following:
S k*A
x= fractional part ofs
h(k)= floor(m*x)

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;

/* start with empty linked list '/


struct Node *start NULL;

/*Create linked list from the array arr[1.


Created linked list will be 1->11->2->56->12 */
for (i = 0; i« 6; i++)
insertAtTheBegin (&start, arr[i));

/ print list before sorting


printf ("\n Linked list before sorting ")
printList (start):
/sort the linked list
bubblesort (start);
/* print list after sorting */
printf("\n Linked list after sorting *)
printList (start);
getchar ():
return 0;

/Function to insert a node at the begining of a linked 1sit *


void insertatTheBegin(struct Node **start_ref, int data)

struct Node *ptrl = (struct Node*) malloc (sizeof (struct Node))


ptrl->data = data;
ptr1->next = *start_ref;
*start ref = ptrl:

Function to print nodes in a given linked list */


void printList (struct Node *start)

struct Node *temp = start;


printf ("\n");
while (temp!=NULL)

DSA-135
POPULAR PUBLICATIONS

printf( "Bd temp->data);


",
temp = temp->next;

*Bubble sort the given linked 1sit */


void bubbleSort (struct
Node *start)
int swapped, i;
struct Node *ptr1;
struct Node *lptr = NULL;

/* Checking for empty list


*
if (ptrl == NULL)
return;
do

Swapped = 0;
ptrl = start;

while (ptr1->next != 1ptr)

if (ptr1->data> ptr1->next->data)
swap(ptrl, ptr1->next);
swapped = 1;

ptri = ptr1->next;
)
lptr = ptr1;

while (swapped);

/* function to swap data of two nodes a and b*/


void swap (struct Node *a, struct Node *b)

int temp = a->data;


a->data = b->data;
b->data = tempP

13. a) Write an algorithm for linear search. WBUT 2017]


an outline of the complexity of your algorithm.
b) Give
Answer:
a)
Linear Search (Array A, Value x)
Step 1: i to
Set 1
step 2: if i > n then go to step 7
Step 3: if Ali] = x then go to step 6
DSA-136
DATASIRUCTURE &ALGORITHM
step 4: Set i to i 1
step 5: Go to Step 2
step 6 PTint Element x Found
step 7 PTint element not
at index i and go to step o

step 8: Exit found

b) Linear search executes in


O(n) time where n is the number of elements in the array
Obviously, the best case of linear
array. In this case, only one search is when VAL is equal to the first element or the
comparison will be made.
Likewise, the worst case will happen
when either VAL is not present in the array or it
equal to the last element of
the array. In both the cases, n comparisons will have to isbe
made.

14. Find the


time complexity of merge
sort technique using the recurrence relation
assuming the size of the list n =2*.
WBUT 2017]
Answer:
Refer to Question No. 7 Long
of Answer Type Questions.
15. a) Explain different types
of data structure operations. WBUT 2019]
b) What is meant by algorithmic
complexity?
c) What is time-space trade-off?
Answer:
a) The basic operations that are performed on data structures
are as follows:
.Insertion: Insertion means addition of a new data element in a data structure.
Deletion: Deletion means removal of a data element from a data structure if it is
found.
Searching: Searching involves searching for the specified data element in a data
structure.
Traversal: Traversal of a data structure means processing all the data elements
present in it.
Sorting: Arranging data elements of a data structure in a specified order is called
sorting.
Merging: Combining elements of two similar data structures to form a new data
structure of the same type, is called merging.

b) Algorithm complexity is a measure which evaluates the order of the count of


operations, performed by a given or algorithm as a function of the size of the input data,
It is a rough approximation of the number of steps necessary to execute an algorithm.
We define complexity as a numerical function T(n) - tüme versus. the input size n.
Big-O notation is the prevalent notation. to represent algorithmic complexity. It gives an
upper bound on complexity and hence it signifies the worst-case performance of the
algorithm. With such a notation, it is easy to compare different algorithms because the
otation tells clearly how the algorithm scales when input size increases. This is often
called the order of growmth.
DSA-137
POPULAR PUBLICATIONS

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

Insertion Sort Selection Sort


Basis For Comparison
The data is sorted by inserting The data is sorted by selecting
Basic
the data into an existing sorted and placing he consecutive
file. elements in sorted location.
Stable | Unstable
Nature Elements are known beforehand
Process to be followed Location is previously known
while location to place them is while elements are searched.
searched.
Immediate data Insertion sort is live sorting| It cannot deal with immediate
technique which can deal with data; it needs to be present at the
immediatedata. beginning
Best case complexity Ofn) On)_
d) For each pass, we will move left to right looking for the next largest value. Once that
is found, it will be swapped into its final position
Step 1:
23, 12, 21, 15, 14, 50, 13.
Step 2:
23, 12, 21, 15, 14, 13, 50
Step 3:
13, 12, 21, 15, 14, 23, 50 Swap 13, 23
Step 4:
13, 12, 14, 15, 21, 23, 50 swap 21, 14
Step 5:
13, 12, 14, 15, 21, 23, 50 no swap, 15 is in correct position

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.

17. Write short notes on the following: WBUT 2010, 20141


a) Radix sort [WBUT 2012]
b) Merge Sort WBUT 2014]
c) Interpolation search WBUT 2015, 2018]
d) Heap
Answer:
a) Radix sort:
Radix sorting is a technique for ordering a list of positive
integer values. The values are
successively ordered on digit positions, from right to left.
This is accomplished by
is given by the position
copying the values into "buckets," where the index for the bucket
examined, the list must be
of the digit being sorted. Once all digit positions have been
sorted.
four
The following table shows the sequences of values found in each bucket during the
146 415 301 730 78 593. During
steps involved in sorting the list 624 852 426 987 269
pass I the ones place digits are ordered. During pass 2 the tens place
digits are ordered,
retaining the relative positions of values set by the earlier pass. On pass the hundreds
3

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

The C-program of the radix-sort is as shown below:


#include <stdio.h>
#include <conio.h>
#define N 11
#define SHOWPASS
void radixsort (int[1, int);
void print (int[1, int);

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)

int i, b[N], m = 0, exp =


1;
int count = 0;
for (i = 0; i < n; it+)

if la[il > m)
m = alil;

while (m / exp> 0)

Count++;
int bucket [10]
={0};
for (i 0; i < n; it+)=

bucket [a[il / exp 8 10] ++;


for.(i = 1; i 10; i++)
bucket [il += bucket [i - 1];
for (i = n - 1; i >= 0; i--)
b--bucket [a [il / exp 8 101] = alil;
for (i = 0; i < n; it+)
alil = b[il;
exp *= 10;

#ifdef SHOWPASSs
printf("\nPASS 8d:", count);
print (a, n);
#endif

void print (int a[l, int n)

int i;
printf("\n");
for (i = 0; i < n; i+*)
printf( "*5d", a[il);

DSA-140
DATA STRUCTURE & ALGORITHM

/* Output of the above program


Before Sorting:
624 852 426 987 269 146 415 301 730 78 593
PASS I:
730 301 852 593 624 415 426 146 987 78 269
PASS 2
301 415 624 426 730 146 852 269 78 987 593
PASS 3:
78 146 269 301 415 426 593 624 730 852 987
Afier Sorting:
78 146 269 301 415 426 593 624 730 852 987

Time complexity of radix sort:


The time complexity of the algorithm is as follows: Suppose that the n input numbers
have maximum k digits. Then the Counting Sort procedure is called a total of k times.
Counting Sort is a linear, or O(n) algorithm. So the entire Radix Sort procedure takes
O(n) time.

b) Merge Sort: Refer to Question No. 1


of Long Answer Type Questions.

) Interpolation search: Refer to Question No. 9 of Long Answer Type Questions.

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

Ina heap the highest (or lowest) priority element is always


stored at the root, hence the
name "heap". A heap is not a sorted structure and can be regarded as partially ordered. As

DSA-141
POPULARPUBLICATIONS

it can be seen from the


picture, there is no particular relationship among
given level, even among the siblings. nodes on any
any
Since a heap is a complete binary tree,
it has a smallest possible height a heap with
nodes always has O(log N) height. N
A heap is useful data structure
when we need to remove the object with the highest
lowest) priority. A common use of a heap is to implement a priority queue. (or

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)

Short Answer Type Questions


1. a) Describe a string
reversal algorithm. WBUT 2012, 2015]
b) What is difference between
Union & Structure? WBUT 2012]
Answer:
a) The C code is given below:
void reverse (char *str) (
char end* = str;
char tmp;

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.

b) The differences between structure and union:


1. Union allocates the memory equal to the maximum memory required by the member
of the union but structure allocates the memory equal to the total memory required by the
members.
2. In union, one block is used by all the member of the union but in case of structure,
each member has their own memory space.

DSA-143
POPULAR PUBLICATIONS

While structure enables us treat


a number of different variables stored at different
memory, a union enables us in
to treat the same space in memory as a number
variables. That is a Union offers a way of different
for a section of memory to be treated as a variable
of one type on one occasion
and as a different variable of a different type on
Occasion. There is frequent requirement another
while interacting with hardware to access a byte
or group of bytes simultaneously
and sometimes each byte individually. Usually union
the answer. is

Long Answer Type Questions


1. a) Write an algorithm
to solve the Tower of Hanoi problem. Also calculate
time complexity of your algorithm. the
WBUT 2007, 2013]
OR,
Write the Pseudocode or C code
to
the complexity of your procedure. implement Tower of Hanoi problem. Also find
[WBUT 2014]
Answer:
Tower of Hanoi (n, source, auxiliary, destination)
If n=1 move disk from source to destination; (base case)
Else,

Tower of Hanoi (top n-1, from, to, using);


Move the nth disk from 'from' to 'tto';
Tower of Hanoi(n-1, using, irom, to);

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
=

T(2)= 8 k2t+ 4k1+ 2k; + k


Coefficient of ki =2"
Coefficient of k=2"-1
Time complexity is O(2") or O(a") where a is a constant greater than
So it has exponential time complexity:
DSA-144
DATA STRUCTURE & ALcORITHM
b) Write the recursive
recursion tree for any function for the Tower of Hanoi problem. Also draw
set of initial valuees. tne
WBUT 2007, 2010]
Write a recursive algorithm OR,
to solve tower of Hanoi problem.
Answer: WBUT 2015]
c function *
void solveTowers (int count, char source,
== 1) char destination,
if (count char spare) t
printf ("Move top disk
from pole" + source +
"to pole" + destinatión);
else
solveTowers (count-1, source, spare, destination)
solveTowers(1, source, destination, spare); ; 7X
solveTOwers (count-1, Y
spare, destination, source) 7
I/ end if i 4
/1 end solveTowers
Recursive tree with n=3.

solveTowers(3,A,B,C)

solvetowers (2,A,C,3) solvetowers(1,A,B,C)solveTowers (2,C,B,A

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

Type of File Organization (column 32) should contain I to specify Indexed-Sequential


organization
The records written to the Indexed-Sequential file being built must be written in
ascending key sequence. If an attempt is made to write a record with a key equal to or
less than the key of the record previously written to the file, HO will be set on and the
program will terminate abnormally.

Processing Indexed-Sequential Files Sequentially


There are no additional entries required beyond those listed above (for building Indexed-
Sequential files) in order to process an Indexed-Sequential file in its entirety. A
sequentially processed file may be used as input (I in column 15 on the File specification)
or update (U in column 15). If processed as an update file, records from the file may be
updated at either detail or total time. The record available for updating is the record read
on the previous input cycle.

Processing Indexed-Sequential Files by Chaining


From one to nine Indexed-Sequential files may be processed by the use of record key
fields specified as chaining fields. A data field in an input record is designated as a
chaining field by placing the chaining field identifier (C1, c2, C3,... C9 in columns 61-
62 of the nput specification). Each chaining field must also be included on an Extension
specification which functions to link the chaining file to the chained file.
During the input cycle, the record key(s) contained in one or more chaining fields are
used to retrieve the corresponding record(s) from the Indexed-Sequential file specified on
the Extension specification. Chaining is the only circumstance in which more than one
record identifying indicator may be on during a single cycle.

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

i The number of possible distinct binary trees with 12 nodes is


4084 c) 3082
d) 3084
4082
a) b)
jjth entry of a (m x n) matrix stored in coiUmn
whicn of the folliowing expressions access the
in) (i.

major order?
a) nx-1)+i b) mx-1)+I c)m x (n-)+j d) n x (m-i) +i

iv) Stack cannot be used to


a) evaluate an arithmetic expression in postfix form
b) implement recursion
o) allocate resources (ike CPU) by the operating system
d) convert infix expression to its equivalent postfix expression

v) The postfix equivalent of the prefix + ab - cd is


a) ab +cd-* b) abcd+-* c) ab + cd"- d) ab +-cd
vi) Merge sort uses
a) divide and conquer strategy b) backtracking approach
c) heuristic search d) greedy approach

vi) 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
a) 2,2,1,2, 1 b) 2, 2, 1, 1,2 c)2, 1,2, 2, 2 d) 2.
1,2, 2, 1

vi) Which of the following is not a requirement of good hashing function?


a) Avoid collision b) Reduce the storage space
cMake faster retrieval d) None of these

) Self-referential pointer is used in defining


a) an array b) a node of linked-list
c)a queuee d) all of these

XA binary tree has n leaf nodes. The number of nodes of degree 2 in


this tree is
a) logn b)n-1 c) n d) cannot be saia
POPULARPUBLICATIONS

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,

3. Write a recursive algorithm to solve tower of Hanoi problem.


See Topic: MISCELLANEOUS, Long Answer "Type Question No. 1(b).

4. Deduce the average time complexity of Quicksort algorithm.


See Topic: SEARCHING & SORTING, Short Answer Type Question No. 8.

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.

6. Write an algorithm to delete the last node of a linked-list.


See Topic: LINKED LIST, Short Answer Type Question No.9

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

b) Insert the following keys in the


order given below to build them into an AVL-tree, 12, 11, 13, 10,
09, 15, 14,; 18, 7, 6, 5, 4. Clearly
mention different rotations used and balance factor of each node.
a) See Topic: GRAPHS, Short Answer
Type Question No. 5.
b) See Topic: TREES, Short Answer
Type Question No. 7

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).

11. Write short notes on any three of the following


a) ADT
b) AVL Tree
c) Circular link list
d) Threaded binary trees
e) Heap
a) See Topic: INTRODUCTION, Long Answer Type Question No.1.
b) See Topic: TREES, Long Answer Type Question No. 17(a).
See Topie: LINKED LIST, Long Answer Type Question No. 5(b)
d) See Topic: TREES, Long Answer Type Question No. 17(b).
e) See Topic: SORTING & HASHING, Long Answer Type Question No. 17(d).

QUESTION 2016S
GROUP-A
(Multiple Choice Type Questions)
Answer any ten questions
1.

9The postfix equivalent of the prefix*


+ ab - cd is

a) ab +cd-* b) abcd +-* c) ab+ed*- d) ab+-cd*


a NULL link of any node it is. replaced by the
1) If a binary tree is threaded for inorder traversal nght
address of its
c)root d) own
a) successor b) predecessor

DSA-149
POPULAR PUBLICATIONS

ii) Adjacency matrix of a digraph is


a) ldentity matrix b) Symmetric matrix c) Asymmetric matrix d) None of these
iv) Linked lists are not suitable for
a) Stack b) Dequeue c) AVL tree d) Binary Search
v) The ratio of items present in a hash table
of the total size,is called
a) balance factor b) load factor c) item factor d) weight factor
vi) Maximum possible height of an AVL tree
with 7 nodes is
a) 3 b)4 c)5 d) 6
vii) The deque can be used
a) as a stack b) as a queue
c) both as a stack and as a queue d) none of these

vi) Inserting a node after a given node in a doubly linked list


requires
a) four pointer exchanges two
b) pointer exchanges
c) one pointer exchange
d) no pointer exchange

ix) The minimum height of a binary trée of n nodes is


a)n b) n/2 c) n/2-2 d) log,(n+1)
x) What will be the time complexity for selections sort to sort an array of n elements?
a) O(logn) b) ofnlogn) d) o()
GROUP- B
(Short Answer Type Questions)
2. Show that the function f(n) defined by

so)=; n=1
sn)=f(n-1)+1/, n>1
has complexity O(In n).
See Topic: INTRODUCTION, Short Answer Type Question No. 2.

3. a) Does a B tree grow at its leave or at its root? Why?


b) In deleting a key from a B tree, when it is necessary to combine
nodes? 'A
c) For what purposes are B trees especially appropriate?
a) &b) See Topie: TREE, Short Answer Type Question No. 10.
e) See Topie: TREE, Long Answer Type Question No. 4(b).

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

10. a) Describe BFS algorithm.


b) Find out the DFS traversal of the following graph starting at node A

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?

a) Stacks b) List c) Strings d) Trees

i) Binary search is not possible for


a) array b) linked list c) stack d) queue

i) The prerequisite condition of Binary search is


a) unsorted array b) ascending order array
c) descending order array d) sorted array

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

v) The number of edges in a full binary tree of height h is


a) 2-1 b) 2-1 c) 2l-2 d) 2-2
vi) Minimum number of nodes required to make a complete binary tree of height h is
a) 2"-1 b) 2 c) 2 +1 d) 2-
vii) A linear link list can be traversed using
a) recursion b) both (a) and (c) are correct
c) stack d) both (a) and (c) are wrong

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

The adjacency matrix of an undirected graph is


b) Asymmetric
matrix
a) Unit matrix
Symmetric matrix d) none of these
c)

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

The data structure used to solve recursive problem is


c) Stack d) none of these
a) Linked list b) Queue

xi) Which one is required to reconstruct a binary tree?


b) Both preorder and postorder sequences
a) Only inorder sequence
d) Only postorder sequence
c) Both inorder and postorder sequences

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.

3. If T(7)=a, +ax +a,r* +a,* .+a,r, then prove T(n) = o(").


See Topic: INTRODUCTION, Short Answer Type Question No. 14.

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.

o.What is Hashing? Write two hash funations. What is collision?


e Topie: SORTING & HASHING, Short Answer Type Question No. 2.

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.

9. a) How a linked-lists can be used to implement stack?


b) Write an algorithm for linear search.
c) Give an outine of the complexity of your algorithm.
a) See Topie: LINKED LIST, Long Answer Type Question No. 4.
No. 13.
b) & c) See Topic: SORTING & HASHING, Long Answer Type Question

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

of the list n = 2".


a) See Topie: SORTING& HASHING, Long Answer Type Question No. 5(a).
b) See Topie: INTRODUCTION, Short Answer Type Question No. 3.
c) See Topic: SORTING& HASHING, Long Answer Type Question No. 14.

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(¢).

12 a) What do you mean by a binary search tree?


b) Constructa binary search tree by inserting the list of elements one by one:
13, 10, 3, 5, 18, 15, 14
c) Write an algorithm for pre-order traversal of a tree represented by a linked-ist.
d) Show that the number of vertices of odd degree in a finite graph is even.
),b)&c) See Topie: TREES, Long Answer Type Question No. 13.
d) See Topic: GRAPHS, Long Answer Type Question No. 1(¢).

13 a) What is an AVL tree?


b) Construct an AvL search tree for the data list
AND, BEGIN, CASE, DO, END, FOR GOTO.
c) For the AVL tree you have constructed delete the following keys in the order:
DO, FOR END
See Topic: TREES, Lang Answer Type Question No. 14.
DSA-154
&ALGORITHM
DATA STRUCTURE

QUESTION 2018
Group-A
(Multiple Choice Type Questions)
1. Choose the correct altematives for the following

Maximum possible height of an AVL Tree with 7 node is


a) 12 b) 4 c) 5 d) 3

i) In a circularly linked list organization, insertion of a record involves


the modification of
d) 3 pointers
a) no pointer b) 1 pointer c) 2 pointers

i) A B-tree is
a) always balanced b) an ordered tree c) a directed tree d) All of these

a complete binary tree of depth k is


) Number of nodes in

c) 2-1 d) None of these


a) 2 b) 2k

v) To make a queue empty, elements can be deleted till


c) front = rear d) None of these
a) front= rear + 1 b) front = rear-
1

vi) BFS constructs


a minimal cost spanning tree of a graphrib) a depth first spanning tree of a graph
a)
d) None of these
c)a breadth first spanning tree

vi) A vertex of in-degree zero in a directed graph is called


b) Sink
a) Articulation point
d) Root vetex
o) Isolated matrix

of every node never differ by more than


Vii) In a height balanced tree the heights of two sub-trees
a) 2 b) 0 c)1 d)-1

0) Inseringa new node after a specific node in a doubly linked requires


a) four pointer exchanges b) two pointer exchanges
d) no pointer exchanges
c)one pointer exchanges
vertices has
A non-planar graph with minimum number of
b) 6 edges, 4 vertices
a) 9 edges, 6 vertices
d) 9 edges, 5 vertices
c) 10 edges, 5 vertices

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 >

has the complexity O(log n)


Let the size of the elements stored in an 8x3 matrix be 4 bytes each. the base address of the
If

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)

1&2nd Part: See Topic: TREES,


3rd
Short Answer Type Question No. 16.
Part: See Topic: GRAPHS, Long
Answer
4 Part: See Topic: GRAPHS, Short Answer Type Question No. 1(c).
Type Question No. 7.
10. a) Define circular queue.
b) Write an algorithm to insert an item in
circular queue.
c) What is input restricted
dequeue?
d) Write an algorithm to convert
an infix
expression to postfix using stack.
a), b) & c) See Topic: STACKS &
QUEUES, Long Answer Type Question No. 3(a),
d) See Topic: STACKS (b) & (¢).
& QUEUES, Long Answer Type Question
No. 2.
11. Write short notes on any three of
the following:
i) AVL Tree
i) Heap Sort
i) DFS
iv) Tail recursion
v)Binary Search Tree
i) Sce Topic: TREES, Long Answer Type Question No. 17(a).
ii) See Topic: SORTING & HASHING,
Long Answer Type Question No. 17(d).
ii) See Topic: GRAPHS, Long Answer Type Question No. 4(d).
iv) See
Topic: MISCELLANEOUS, Long Answer Type Question No. 2(b).
v) See Topie:
TREES, Long Answer Type Question No. 17(d).

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

) Which among the following are applications of queues?


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 parsing9
d) None of these

i) A full binary tree with n non-leaf nodes contains


a) log 2n nodes b) n+1 nodes c) 2n nodes d) 2n+1 nodes

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

vii) The postfix equivalent of the prefix expression +ab cd is


-

a) ab+cd-* b) abcd+ c) ab + cd- d) ab+ cd

vii) Linked list is a


a) Linear data structure b) Dynamic data structure
c) Self referential data structure d) all of these

ix) One limitation of linked list is


a) it requires huge memory space requires contiguous memory space
b) it
c) nodes can only be accessed sequentially d) nodes can only be accessed randomly

x) What is the worst case performance of Selection sort algorithm?


a) Oflog n) b) O(nn) c)O(n) d) Ofn log n)

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

xi) Recursion uses more memory space than iteration because


a) it uses stack instead of queue b) every recursive call has to be stored
c) both (a) and (b) d) none of these

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.

3.Write the algorithms for PUSH


and POP for linked representation of stack.
See Topic: STACKS & QUEUES,
Short Answer Type Question No. 9.

4. Explain with suitable example


the collision resolution scheme using linear probing with open
addressing.
See Topic: SORTING & HASHING,
Short Answer Type Question No. 2.
5.Write an algorithm to delete
a node having value NUM from a Doubly linked list.
See Topic: LINKED LIST,
Long Answer Type Question No. 1(b).

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?

c) How can the polynomial 4x +7x +2 be represented using a linked list


and an array? Also
explain why arrays should not be used in this regard.
d) What is the necessity of having circular queue?
a) See Topie: GRAPHS, Long Answer Type Question No. 3.
b) See Topic: STACKS &QUEUES, Short Answer Type Question No.
2(1" Part).
) See Topic: LINKED LIST, Short Answer Type Question No. 15.
d) See Topiec: STACKS & QUEUES, Short Answer Type Question No.
5(b).

8. a) How does AVL tree differ from binary search tree?


D)Explain different rotation mechanisms in AVL tree.
) Build an AVL tree with nodes inserted in the following order
8. 12, 9, 11, 7, 6, 62, 15,3
Ciearly mention different rotations used and balance factor of each node.
0) Show that for a non-empty binary tree, if n, is the number of leaf nodes and n, is the number of
nodes of degree 2 then n, =n2 +l.
) See Topic: TREES, Long Answer Type Question No. 10(b) (1" Part).
D) &
d) See Topic: TREES, Long Answer Type Question No. 15(a) & (b).
See Topic: TREES, Long Answer Type Question No. 10(b) (2d Part).

DSA-159
POPULAR PUBLICATIONS

9. a) Create a binary search tree using the following data elements:


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.
c) Write down the algorithm for deleting a node from a binary search tree considering all
D
ssitble
cases of number of children.
a) &b) See Topie: TREEs, Long Answer Type Question No. 16(a) & (b).
e) See Topic: TREES, Long Answer Type Question No. 3(b).

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)& ().

11. a) Explain selection sort algorithm.


b) Write an algorithm for selection sort
c) Compare selection sort with insertion sort.
d) Sort the following data using selection sort algorithm (show the intermediate outputs)
23, 12, 21, 15, 14, 50, 13
See Topie: SORTING & HASHING, Long Answer Type Question No. 15(), (b), () & (d).

DSA-160

You might also like