Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Fundamentals of

DataStructures
SPPU-CBCs SCHEME-2019/2020 SYLLABUS-S.E. (COMP/AI&DS) SEM I -

Sub. Code: 210242

Written by Popular Authors of Text


Books of Technical
Covers Entire Syllabus Question Publications
Answer Format
-

Exact Answers and Solutions


.Chapterwise Solved SPPU Questions Dec. 2009 to June
Solved Mode Question Paper 2022
(As Per 2019 Patern)
SOLVED SPPU QUESTION PAPERS
May 2017 Dec. 2017 May 2018
Dec. 2018 May 2019 Dec. 2019
June 2022 [Course 2019

first edition : nov. 2022

DECODE
AGuide for
Price:105/-
ISBN 978-93-558-101-7

Engineering Students
www.e wise

Unit

Introduction to Algorithm
and Data Structures

1.1: From Problem to Program and


Concept of Data Structures

Q.1 Define the term Data structure.


data structure is particular way of organizing data in a
Ans.: A a

computer so that it can be used effectively.


For example - Consider set of elements which can be stored in array data
structure. The representation of array containing set of elements is as

follows
0 1 2 4
10 20 30 40 50

Q.2 Give the difference between Data and Information.

Ans.

Data Information.
Sr. No.
1. Data is in raw form. Information is processed form of
data.

2 Data may or may not be Information is always meaningful.


meaningful.
3. Data may not be in some Information enerally follows
specific order. specific ordering.
4. For example Each student's For example The average score of
marks in exam is one piece of a class is information that can be
data. derived from given data.

(1 - 1)
Data Structures
Sructures

D'ata
Fundamenalsof
Data Structures
Abstract

1.2:
for an
an arrays.
arrays,
Write
ADT for
?
What is
ADT
Dec.-11,-11, Marke
Marks g8.
6, May-12, Marks
Q.3 May-10,11,
4
[SPPU:
of D
inle of D SSet ofdow
data type
is triple
a
et
of domains, F Set of
.

abstract
what is to be
only wha
only done is mentioned
Ans.:
The
axioms in which
which but
functions,
A mentioned.

not
done is
how is to be hidden.
details are
implementation
the
In ADT, all
AbstractData1ype Array

size, inaex 1 and total numher e

Instances: An array A of some


n.
elements in the array

Operations
stores the desired elements at each successive
Store ()- This operation
location.
elements of the array.
display ()
-

This operation displays the

04 Define (1) ADT (2) Data Structure. i [SPPU May-19, Marks 21

Ans.: Refer Q.3 and Q..

1.3: Data Structure Classiflcatlon

Q.5 Write short note on Linear and Non-Linear data structure with
example.
0SPPU : Dec.-19, Marks 4
OR Differentiate between linear and non linear data structure with
example.
SPPU May-17, Marks 3]
Ans.:Linear data structures are the data structures in which data s
arranged in a list or in a
straight sequence.
For example: arrays, list.
Non linear data
structures are the data structures in
arranged in hierarchical which data may
manner. For
example : trees, grapns
ICOD
A Gulde for Emgineertng Students
orithm
ctures Introducthon to Algorithm
and Data Structures
Fumdamentals of Data Structures 1-3

Q.6 Explain static and dynamie data structures with examples.


SPPU : Dec.-18, Marke 4
s4 Ans.: The static data structures are data structures having fixed size
tof memory utilization. One has to allocate the size of this data structure
but before using it.
For example (Static Data Structure)
Arrays in C is a static data structure. We first allocate the size of the
arrays betore its actual use. Sometimes what ever size we have allocated
for the aays may get wasted or we may require larger than the one
which is existing. Thus the data structure is static in nature.
of The dynamic data structure is a data structure in which one can allocate
the memory as per his requirement. If one does not want to use some
block of memory, he can deallocate it.
ve For example (Dynamic Data Structure)
Linked list, the linked list is a collection of many nodes. Each node
consists of data and pointer to next node. In linked list user can create as
much nodes (memory) as he wants, he can dellocate the memory which
cannot be utilized further.
The advantage of dynamic data structure over the static data structure is
that there is no wastage of memory.

1.4:Problem Solving

Q.7 State a reason why each of the six problem solving steps is
important in developing the best solution for a problem. Give one
reason for each step. SPPU: May-10, Marks 8]
OR Consider any one problem and solve that problem using six
steps of problem solving. Explain each step in detail.
K[SPPU: Dec.-10, Marks 81
OR Describe the six steps in problem solving with example.
[SPPU May-11, Marks 8]
Ans.: Problem solving is based on the decisions that are taken.
Following the six steps of problem solving
are -

I Identify the problem: Identifying the problem is the first step in


solving the problem. Problem identification is very essential before
solving any problem.
PECODE) A Gulde for Engineering Students
Introduction to Algorithm
1-4 and Data Structures

Fande
Before
olving any
solving any problemit is important
problem

:Uderstand
the
problem
aspects
three aspects
based on which the problem
ere are
are
There
understand
it.

can e understood

While solving
he problem
the problem the
prohleBEDase knowledgebase
.Knowiedgebase machine.I
or a
Iff the problem is to be
to a person
be related what the to know
to
then it is
can necessary
the person solved for the machin
machine then
soved for is to be solved
knows. Ifthe
problem
person known. Along with
this the problem
problem
set must be
instruction
its own instruction
set.
make use of his/her
solver can
the subject on which the
.Subject:
Before solving the problem
knoWn. For instance To solve the
is based must be
problem knoW about the
t is necessary to
problem involving Laplace,
Laplace transform.

Communication For understanding the problem, the developer


must communicate
with the client.

ways to solve the problem The alternative


3. Identify the alternative known to the developer. These
way to solve the problem must be
alternatives can be decided by communicating with the customer.
4. Select the best way to solve the problem from list of alternative
solutions For selecting the best way to solve the problem, the merits
and demerits of each problem must be analysed. The criteria to
evaluate each problem must be predefined.
5. List the instructions using the selected solution : Based on the
knowledgebase (created/used in step 2) the step by step instructions are
listed out. Each and every instruction must be
understood by the person
or the machine involved in
the problem solving
process.
6. Evaluate the solution
whether the solution is correct
When the solution is evaluated then i) Check
or not ii) Check whether it satisfies the
requirements the customer or not.
of

1.5 Dificulties in Problem


Solving
Q.8 State and
explain any four difficulties with problem
solving
[SPPU Dec.-10, Marks 4
pIcODL
A Gulde for Engineering Students
Introductton to Algorithm
1-5 and Data Structures
Fundamentals of Data Structures

OR What are the diffculties in problem solving ? Explain any four


steps in problem solving suitable example.
[SPPU May-16, Marks 4]
Ans.: Various difficulties in solving the problem are

People do not know how to solve particular problem.


Many times people get afraid of taking decisions
While following the problem solving steps people complete one or two

steps inadequately.
People do not define the problem statements correctly.
They do not generate the sufficient list of alternatives. Sometimes

good
alternatives eliminated. Sometimes the merits and
might get
demerits of the alternatives is defined hastily.
The sequence of solution is not defined logically, or the focus of the
design is sometimes on detailed work before the framework solution.
.When solving the problems on computer then writing the instructions
for the computer is most crucial task. With lack of knowledgebase one
can not write the proper instruction set for the computers.

1.6 Introduction to Algorithm

Q.9 Define Algorithm and its characteristics.


SPPU : Dec.-16, Marks 4, May-19, Marks 2]
Ans.: Definition of Algorithm An algorithm is a finite set of
instructions for performing a particular task. The instructions are nothing
but the statements in simple English language.
1. Each algorithm is supplied with zero or more inputs.

2. Each algorithm must produce at least one output.


3. Each algorithm should have definiteness i.e. each instruction must be
clear and unambiguous.
4. Each algorithm should have finiteness i.e. if we trace out the
instructions of an algorithm, then for all cases the algorithm will
terminate after finite number of steps.

A Gulde for Engineering Students


(DECODD
wmdamen talt of Data Strnc tures
Introduction to Algorithm
and Data Structure
Tach algonthm should have eftectiveness i.e. every in.
ficiently hasic that 1 can in principal be carried
ed
instruction must he
onis pencil and paper. Moreover Cach instructionout by
of an algorith
aperor
muet also he feas1ble.
persor

1.7: Aigorithm Design Tools


.10 What do you mean by flow chart ? Give the
smbol used in flowchart. Draw flowchart to
meaning of ea
compute the sumn of
elements from a given integer array.
[SPPU May-10, Marks 8
Ans

Start

Read array
elements

Sum = 0

i= 1 1 n

Sum Sum +alil

Display Sum

Stop

Fig. a.10.1

riue Sudenrs
Introduction to Algorthm
Fundamentals of Data Structures 1-7 and Data Structures

a.11 Design and explain an algorithm to find the sum of the digits
of an integer number. [SPPU: Dec.-10, Marks 6]
Ans.
Read N
Remainder=0

Sum=0

Repeat
Remainder=N mod 10
Sum=Sum+remainder
N=N/10
Until N<0
Display Sum
End
Q.12 What is a difference between flowchart and algorithm ?
Convert the algorithm for computing factorial of given number into
flowchart. SPPU May-11, Marks 8]
Ans. Algorithm is a set of Start
instructions written in natural
language or pseudo code and
Read the
flowchart is a graphical
number'n
representation of an algorithm.

Read N
fact 1

Set i andF to 1
While i< =N i 1 1 n
F=F *i
Increase the value of i by 1
Display F fact fact» i
End
Print the value
of fact

Stop
Fig. Q.12.1 Flowchart for factorial

A Guidefor Engineering Sudents


pICODD
Fundamentals of Data
Structures
nd Datato Structures
Algorith

1.8: Step Count Method

count method ? Explain


it with exam
Q.13 What is step ample.
frequency count 1S a count that that denotes ho,
Ans. Definition: The statement is executed.
many times particular

Example: Consider following


code for counting the freau
For frequency cOun
void fun()

int a,
..1
a=10;.
printf(%d",a); . .

The frequency count of above program is 2.

1.9:Complexity of Algorithm
Q.14 What is time complexity ? How is time complexity of an
algorithm computed ?
[SPPU : Dec.-11, Marks 6|
Ans.: The amount of time required by an algorithm to execute is called
the time complexity of that algorithm.
For determining the time complexity of particular algorithm following
steps are carried out
1. Identify the basic
operation of the algorithm.
2. Obtain the frequency count for this
basic operation.
3. Consider the order
of magnitude of the frequency count and express
in terms of big oh notation.
Q.15 Write an
algorithm to find smallest element in
arTAY a
integers and analyze its time complexity. p
ISPPU: May-13, Mar ks
Ans.
Algorithm MinValue(int ain])

min_element=a[0];
QECODD rdens

A Guide for Engineering Sue


Introduction to Algorthm
Fundamentals of Data Structures 1-9 and Data Structures

for(i-0;i<n;1+ +)

if (alil<min_element) then
min_element=a[i);

Write(mín_element);

We will first obtain the frequency count for the above code

Statement Frequency Count

1
min_element=a[0]
for(i-0;i<n;i++) n+1

if(a[i]<min_element) then n

1
Write(min_element);
Total 2n+3

By neglecting the constant terms and by considering the order of


magnitude we can express the frequency count in terms of Omega
notation as O(n). Hence the frequency count of above code is O(n).
Q.16 What is space complexity of an algorithm ? Explain its
importance with example.
D[SPPU Dec.-10, Marks 4]
Ans.: The space complexity can be defined as amount of memory
required by an algorithm to run.

To compute the space complexity we use two factors Constant and


instance characteristics. The space requirement S(p) can be given as

S(p) = C+Sp

where C is a constant i.e. fixed part and it denotes the space of inputs
and outputs. This space is an amount of space taken by instruction,
variables and identifiers. And Sp is a space dependent upon instance
characteristics. This is a variable part whose space requirement depends
on particular problem instance.

PECODD AGuidefor Engineering Students


Introduction to Algorithm
Fundamentals of Data Structures 1- 11 and Data Structures

Definition

Let fn) and gln) be two non-negative functions.


Let no and constant c are two integers such that ng denotes some value
o finput and n > no. Similarly c is some constant such that c > 0. We

can write

f(n)sc'g(n)
then fn) is big oh of g(n). It is also denoted as fn) e O (g(n)). In other
words fn) is less than g(n) if g(n) is multiple of some constant c.

Cg(n)

f(n)

n
no
fn) e O(g(n))

Fig. Q.18.1 Big oh notation


2. Omega Notation : Omega notation is denoted by '2'. This notation is
used to represent the lower bound of algorithm's running time. Using
omega notation we can denote shortest amount of time taken by
algorithm.
Definition
A function f{n) is said to be in 2 (g(n)) if fn) is bounded below by some
positive constant multiple of g(n) auch that
f(n) 2 c * g(n)

For all n 2 no
It is denoted as f(n) e 2 (g(n)). Following graph illustrates the curve for
2 notation.

QECOD) A Guide for Engineering Students


Structures
I- 12 Introduction to Algorlthm
and Data Structures
Fundamentals
of Data

f(n)

C9(n)

n
no
Fig. Q.18.2 Omega notation f(n) e 2 (g(n))

3. Notation: The theta notation is denoted by . By this method the


time is between upper bound and lower bound.
running
Definition
Let fn) and g(n) be two non negative functions. There are two positive
constants namely c1 and c2 such that

C1 g(n) s c2 g(n)
Then we can say that
fn) E (g(n))

C2 *g(n)
f(n)

Cg(n)

n
no
Flg. Q.18.3 Theta notation f(n) e (g{n)

IcODD A Gulde for Engineering


Students
hm
Introducthon to Algorithm
res Fundamentals of Date Structures 1-13 and Data Structures

1.11: Analysis of Programming Constructs


Q.19 Find the frequency count (F.C.) of the given code
Explain each step.
double IterPow(double X, int N)
double Result = 1;
while (N > 0)

Result Result *X;


N-;

return Result;

SPPU : May-10, Marks 6]1


Solution
Statement Frequency Count

double Result=1

while(N>0) N+1
Result-Result*X N
N N
return Result

Total 3N+3
Q.20 What is frequency count of a statement ? Analyze time
complexity of the following code:
i) for(i 1; i<=n; i++)
for 1; j <= m; i++)
for(k = 1; k <= p; k++)
sum=sum + i;

while(i 2 1)
SPPU Dec.-11, Marks 6, May-14, Marks 3

CIcODE A Gulde for Engineering Sudents


Fundamentals of Data Structures I-14 Introducton to Algorlthm
and Data Structure

Solution: i)
Statement Frequency Count
for(i-1;is=n;it+) n+1

for(j-1j<=mj++) n(m+1)
fordk-1;k=p:kt++) n.m.(pt+1)
sum=sum+i | n.m.p
Total 2(n+nm+nmp)+1
ii)

Statement Frequency Count

while(i>=1) nt1

Total 2(n+1)
Q.21 Determine the frequency counts for all the statements in the
following program segment.
i=10;
fori=10;i<=nzi++)
forg-1:j<i:j++)
x=x+1;
SPPU : May-13, Marks 6)
Ans. Assume (n-10+2)=m. Then the total frequency coúnt is -
The outer loop will execute for m times.
The inner loop is dependant
upon the outer loop. Hence it will be
(m+1/2. Hence overall frequency
count is (1+m+m*)(m(m+1)/2)
If consider only the order of
we
magnitude of this code then overall time
complexity in terms of big oh notation is O(n^).

DECQREY
Introduction to Algorithm
Fundamentals of Data Structures 1 - 15 and Data Structures

Statement Frequency Count

i-10;
for(i-10;i<=n;it+) m (we assume the count of execution is m)

forj1j<ij+) m(m+1)/2)
x=X+1; mm)

If an algorithm takes time O(logn) then it is faster than any other


algorithm, for larger value of n. Similarly Ofnlogn) is better than O(n*).
Various computing time can be O(1), O(logn), O(n),0(nlogn), O(n°),
Ofn) and O(2").

1.12 Recurrence Relation

Q.22 What is recurrence relation ? Explain with example.


SPPU:Dec.-18, Marks 2]
Ans. : Definition: The recurrence equation is an equation that defines a
sequences resursively. It is normally in following form

T(n) =T(n -1) +n for n> 0(1)

Recurrence relation
T(0) = 0
(2)

Initial condition

The recurrence equation can have infinite number of sequence.

The general solution to the recursive function specifies some formula.

For example : Consider a recurrence relation


Tn) 2T (n - 1) + 1 for n>1
T(1) = 1

By solving this relation we will get T(n) = 2" -1 where n> 1.

QECODE A Guide for Engineerlng Students


Introduction to Algorithn Introduction o Alzorith
1-17 and Deta Structures
1- 16
and Data Structwe Fundamentals of Data Structures
Structures

Data
Fundamentals ef
Relation
Recurrence
1.13 Solving
T(n) = T ( n _- 1)1

the
following
r e c u r r e n c e
relation

Also find big oh notation -4zc|-c


.23 Solve initial
condition.

with T0) = 0 ss

=
+7C
Ans.:Let 1)+ I1
Tn)= T(n -
By hackward s u b s t i t u t i o n .

1
-

23 n
a3 -1)C
Tn 1)= T(n -2)
+1
T(n)
=

T (n - 1)
1
(Tn 2) +1) Tn) = 2k
2) + 2
T(n) =
T(n -

2 1) 1 If we 2 = n theen
T(n
-

2)
-

Again Tn
-

= T(n - 3) + 1 T(n) = nT|(n-1)C


T(n) =
T(n -

2) +2
= nT(1) +(n - 1) C
(T(n -3)+ 1)+2 T(1) = 1
T(n) =
T(n -

3) +3 T(n) =
n + (n -

1) C
ii) Let,
(1)
T(n) =
T(n -

k) + k
T(n) T(3C
If k = n then equation (1) becomes

T(n)= T(O) + n
= 0+n T(0) 0 ).c-c
T(n)= n -
2C
We can denote T(n) in terms of big oh notation as
T(n) = O(n)

a.24 Solve the following recurrence relations -

To)- 2 C T(1) 1 i) T(u) =

T| c T)-1.
3C
Ans.: i) Let

T(n) C
T Ta -a)-n
T
a
Ta 2-1)

2s What is Master's method


ARs.: We can sohe numene rlation
Masers method
using a imula denotad dy
r a s v t n (a. z -

1 a'n] Ta) =

aT (n b) F(n) where n 2 d and d is some constant


Then the Master heorem can be stated for etticieney
ra aa Mais tmsla nr the atvre vde analysis as
and solve this If Fa) is e(n) where d 20 in the recurence relation
then.
k ha v ta
troin T(n)=end)
u t ys enecuted at least ifa b
2. T(n) (nd log =
n) if a b
a sisn
tya, ters
1 a
t ts tall t the functin sum, by 3 T(n) =On°sba
changing ifa>b
Q.27 Solve the
following recurrence relation.
Tn) 2T(n/2) + n log n
Wa ti dn
this r66u1ne Ans.
1elatim using
backward substitution. Here f(n)=
It will n
log n
T( Tn-1) a= 2, b =2
log2 2 1
f
recursive or
Count According to case 2
given in above Master theorem
all to funotion slatelnent
um in glse fn) =
(n %2 log'n) i.e. k 1
Then T(n) =
(nsa log
Beesbe n)
1- 12 und bula trues
StrurtuTs
Fundamanial1 of Data Fundumentads of Dota Struetue - 19

-[T(n-2) 2) 2
T (-2r2)
IT-3) 2) 2
T(1-k T n - 2 ) - T(n -3) - 3 (2

Ta) = C iogn- 1 TO)-


vde:
2 5 Cosider
the lbrring T(n) T(n - n) n (2
izh wn (izd a [ )
- TG) 2

runt =
C 1
2 2 T9)-2
Tn) 2n+1)
1 We can derane the tine umpizity in e tn d n h urasn a
ot= cunt +
return 0; 0n)
a24 What is Master's method ?
eise ie vive reitsn uin a f r l a deru vy
Ans. can reorens

= unt + 1 Masters method


wt
Fln) whae 2 d zrd d is v e u n s a t
rean um (a, n -

1)+ainj; T(n) aT (n/b) n

Then the Masr thenan ca te uard fr efficiency analyis at

the Telatin then,


the recurvive furmula or the above cde and swtve th
1f Fny is Gn°) where d 2 ) in recurreTK

Write
r e u r r e n e relation Tn) n ) ifa b
zet yets executed a leas if a b
in e avve u e the fullwing
Ans. :

1w Tn) Gn P ifa b
e a s i v e call v the functin sum, by changins relatíon.
In the else pen, thre is a Q27 Soive the following
recurrence

th vahue i n by rn 1, e h time
-

Tn) 2T(n/2) + n og n

H e n the eoasive frrmula


fn above ude will be
Ans.
TG)=2 Here fn) n log n
hackward substitutiom. It will
We can ulve this recurence relation using a2, b 2
1
log2 2 Master theorem
T(n) T(n - 1, According to case 2 given in above k
ie.
For court
fn) e n "62 log'n)
For recursive
a l to functionatement
Then Tn) e (n"6° log'n)
Sum in 6lse Stua
A Gulde for Engineertng
part
IcoDD
Students
A Guide for Engineering
uCtutes
Sructures

Fundamentals ofData
Fundamentals of Data Struetures Introduction to Algorithm
1-21 and Date Structures
-( n 2 log*n)
- e(n 'log*n) T(n)- e(n*)
Hence the complexity of given recurrence relation is n).
T(n) (n log*n) Q.30 Solve recurrence relation T(n)
recurrence
relation T(n) =
9T (n/3) + 3
-
k T (mi k) +m*when T(1) -
1,
a.28 Solve the following and k is any constant.

Solution Ans. Let,


n
9, b 3 and fn) =

Tn) kTn2
=

Here a =

And log 9 =2

According to case 3 in above Master theorem be a recurrence relation. Let us use substitution method
If we assume k = 2 then the equation becomes
AS fn) is =
Q (n°839+
have fn) =ns. T) = 2 7 n 2
i.e. Q(n2E) and we
Then to have f(n) =2(n). We must put e =1.
T(n) = O(f(n)
Then
Then Tn) e(fn))
Tn) =e(n

a.29 Find the complexity of the following recurrence relation. -


T() 9T(a/3) + n
Solution: Let T(n) = 9T (n/3)+ n

a b f(n) L
.We get a = 9, b =3 and f(n) =
n.
= 8T
%3n2
Now fn) n
a-
Tn) n)-e(n ) =@n2-)
When&-1. That means case 1 is
applicable. According to
time complexity of such
equatíons is
case 1, the
2*T +Cn2 C Constant
Tn) n " )
Ifwe put=1 then 2 =n andk- log2n
-9n')
-nT(1)+Cn
A Gulde (r Eaetacerduu Studetnt
pucoD A Gulde for Engineertng Studens
Fundamentale of Date Sttueture Introduction to Algorithm
T(1) and Data Structures

Tn)A (n)* The time complexity that we get for certain set of
same. Then for corresponding input such a time inputs as a isaverage
is

Alternate Method average case time complexity compiexity called


recurrence
relation using Master's theorem also,
We can solve the given Consider the following algorithm
2
Tm)-T n Algorithm Seq_search(%[0.. n-1 |key)
I Problem Description: This algorithm ia tor
searching tte
I/key element from an array
a b fn) X{0.n-1 sequentially
/Input: An array X[0...n-1] and search key
n" n08kK=nl
By Master'stheorem
=

/Output: Retums the index of X where key value is present


For T(n)= f(n) we need for i - 0 to n-1 do

T(n) nloskh+
e
Applying case 3 (X[i=key)then
return i
ntI when e= 1
Best case time complexity
f(n) i.e. n
Best case time complexity is a time complexity when an
algorithm runs
T(n) = e(f(n)) for short time. In above searching algorithm the element key is searched
from the list of n elements. If the key element is present at first location
T(n) n 2 ) in the list(X[0...n-1]) then algorithm runs for a very short time and
thereby we will get the best case time complexity. We can denote the best
1.14 Best, Worst and Average Case Analysis case time complexity as
best1
Q.31 Explain Best case, worst case and average case analysis. Worst case time complexity
Ans.: If an algorithm takes minimum amount of time to run to Worst case time complexity is a time complexity when algorithm nns for
completion for a specific set of input then it is called best case time a longest time. In above searching algorithm the element key is searched
complexity. from the list of n elements. If the key element is present at n location
then clearly the algorithm will run for longest time and thereby we will
For example : While searching a particular element by using sequential get the worst case time complexity. We can denote the worst case time
search we get the desired element at first place itself then it is called best complexity as
case time complexity. worst n
The algorithm guarantees
that for any instance of input which is of size n,
If algorithm takes maximum amount of time to run
an
tocompletion for a the nunning time will not exceed Cwos(n). Hence the worst case time
specific set of input then it is called worst case time complexity gives important information about the efficiency of algorithm.
complexity.
For Average case time complexity
example : While searching an element by using linear
method if desired element is searching This type of complexity gives information about the behaviour of an
placed at the end of the list then we get algorithm on specific or random input. Let us understand some
worst time complexity. that for computing average case time
terminologies are required
Complexity.
CIcODD A Guidefor Engineering Students
A Gulde for
Engineering Students OIcODD
Introduction to Algori
1-24
and Data Structure
Structures
Fundamenials
of .
Data Introduction to Algorithm
search and
Fundamentals ofData Structures 1-25 and Data Structures
is for sequential
Let the algorithm search.
successfül
1.15: Introduction to AlgorlthmicDesign Strategles
P be a probability of getting
of elements in the list.
number
n is the total nro a.32 What is algorithmie design statregy ?
at i location. Hence
The first match
of the element
for every
will occur

i" element.
ability Ans.: Algorithm design strategy is a general approach by which many
first match is P/n These problems may belong to
of occurring
problems canbe solved algorithmically.
unsuccessful search is (1 -

P).
The probability of getting different areas of aputing. Algorithmic strategies are also called as
Now, we can find average case time complexity Cavg n) as algorithmic techniques or algorithmic paradigm.
with suitable
Probability of successful
search Q.33 What is divide and conquer strategy ? Explain it
Cavg (n)
=

(for elements I to n in the list)


example. [SPPU Dec.-19, Marks 3
Ans. In divide and conquer method, a given problem is,
+Probability of unsuccessful search
There may be n| 1) Divided into smaller sub problems.
n (1-P) elements at which These sub problems are solved independently.
Cmg)-1-2 L chances of 'not
2)
3) If necessary, the solutions of the sub problems are combined to get

getting element| a solution to the original problem.


-

[1+2+. +i..n]+
n
n (1-P) are possible. Hence|
If the sub problems are large enough, then divide and conquer is

n.(1-P) reapplied.
nP
n
nn+1)
2
+n (1-P) The divide and conquer technique is as shown in Fig. Q.33.1.

Cavg(n) = P (n+ + n (1-P) Problem of size n

Thus we can obtain the general formula for computing average case time
complexity. Sub problem 1
Suppose if P = 0 that means there is no successful search i.e. we have Sub problem 1
of size n/2
of size n/2
scanned the entire list of n elements and still we do not found the desired
element in the list then in such a
situation,
Cavg (n) = On + 1/2 + n (1 - 0)

Solution to
Cavg(n) n Solutionto sub problem 2
Thus the average case sub problem 1
running time complexity becomes equal to n.
Suppose ifP I i.e. =
we successful search then
get a

Cavg (n) 1 (n+ 12 +


n(1 1) -

Cavg (n) (n + 1)2 Solution to original


problem
That means the
algorithm scans about half of the elements
from the list.
Divlde and conquer technlque
Flg. Q.33.1
Fuaineerine Sudents
Introducton to Algorthm
Introduction to Algorth and Date Structures
and Data Structure 1-27
1-26 Fundamentals of Data Structures
Structures

F u n d a m e n t a l s

of Data with suitable eample. Commes


the orie
usually
of same type as
Q.34 Explain the greedy strategy
sub problems
are
usedi in divide its time complexity. (SPPU : Dec.17, Marks 61
.Thegenerated sometimes
recursive
algor+thms
are
and on
Hence solutioas.
problem.
Ans.: This method
is popular for obtaining the optimized
conquerstrategy
Greedy technique, the solution is constructed through a sequence of
Example: Merge Sort
the divide and con .In
obtained so far,
that uses
nquer steps, each expanding
a partially constructed solution
sort is a sorting algorithm carried out. reached.
T h e merge
method
division is dynamically until a complete solution to the problem is
In this
strategy.
withn elements
consists of three stens activities performed.
on an input array .In Greedy method following are

Merge sort s2 with n/2 elements domain.


two sub lists sl and 1. First we select some solution from input
Divide: partition array into
2. Then we check whether the solution is feasible or not.
each.
sort sub list s1
and sub list s2. solutions, particular solution that
satisfies
3. From the set of feasible
Conquer: Then solution is
and s2 into a unique
sorted group. satisfies the objective of the function. Such a
Combine: merge sl
or nearly
called optimal solution.
as
Consider the elements
As Greedy method works in stages. At each stage only one input
10, 50, 60 4.
70, 20, 30, 40, is considered at each time. Based on this input
it is decided
this list into two sublists.
whether particular input gives the optimal solution or
will split not.
Now we

70 20 3040 10 50 60
Example of Greedy Method
Divide shortest path
Divide .Dijkstra's Algorithm is a popular algorithm for finding
source shortest
40 10 50 60 using Greedy method. This algorithm is called single
70 20 30 path algoithm.
Divide Divide
I n this algorithm, for a given vertex called source the shortest path to

7020 40 10 50 60 all other vertices is obtained.

Divide Divide In this algorithm the main focus is not to find only one single path but
to find the shortest paths from any vertex to all other remaining
40 50 60 vertices.
Merge Merge This algorithm applicable to graphs with non-negative weights only.
2070 30| 10 40 50 60 Consider a weighted connected graph as given below.

Merge Merge
20 30 70 10 40 50 60 7
Merge Merge 8 3
|10 20 30 40 50 60 70
Fig. Q.33.2
A Guidefor Engincering Students
OacODD A QIcODD
Gulde for Engineering Students
ntroducflu
duction to Algoriu
and Data St
1-28
dametals of
Data
Structures

ture
un
as a source and will find
wit

ning vertex. Lethe


verlex
cach
consider
will other remainino
Now we
vertex to every
from this
shortest
distance
Unlt II
start with vertex A
Path shown in graph
us

with other
vertices|

2
Distance
Source
Linear Data Structure
vertex
3
path-4
using Sequential Organization
A-B,
path 8
A-C,

A-D,
path oo
8 3
2.1 Concept of Sequential Organization
A-E path
3
B B-C, path =4+1 Q.1 What is arrays ?

B-D path =
4 + 3 8 Ans.: Defintion of Arays: Aray is a set of consecutive memory
path= o
locations which contains similar data elements.
B-E 3
Array is basically a set of pair-index and the value.

C 5 + 7 12 3 Syntax
C-D, path
path 5+ 3 8 data_type name_of _array [size]
C-E, 8
For example, int a [10]; double b[10] [10];
3
Here a' is the name of the array inside the square bracket size of the
array is given. This array is of integer type i.e. all the elements are of
D D-E, path 7+ 8 15
integer type in array 'a'.
But we have one shortest distance obtained from A to E and that is Q.2 Give the advantages and disadvantages of sequential
A B C E with path length 4 + 1 +3 8. Similarly other organization of data structure.
shortest paths can be obtained by choosing appropriate source and Ans.: Advantages of sequential organization of data structure
destination.
1. Elements can be retrieved stored very
or efficiently in sequential
Dijkstra's Shortest path algorithm take oElogV+VlogV) time, where organization with the help of index or memory location.
E is number of edges and V is number of vertices of a
graph. 2. All the elements are stored at continuous
memory locations. Hence
searching of element from sequential organization is easy.
Disadvantages of sequential organization of data structure
END..
1. Insertion and deletion of elements becomes
complicated due to
sequential nature.
2. For storing the data large continuous free block of memory is required.
3. Memory fragmentation occurs if we remove the elements randomly.
pIcoD A
Guide for Engineering Students
(2-1)
Linear Data Structu
2-2
using Sequentlal Organlzaton
Structures

F u n d a m e m t a l s of Data Linear Data StructurTe


Data Type Fundamentals of Data Structures 2-3 ustng Seqwntial Orzantzation
Abstract

Array as
an
2.2:
Then it will look like this-
ADT for
Arrays. Colurmn
Write an
Q.3

Ans
AbstractDataType Array

row 10 20 30
index 1 and total number of
of some size,
Instances An array A 40 50 60
n.
elements in the array

Operations:
creates an array.
1. Create () This operation
the element in an array
2. Insert) operation is for inserting
This
the elements from the
3. Delete() This operation is for deleting
-

deletion of the element is possible. 9


array. Only logical
elements of the array. two dimensional array should be in row-colmn form.
4. display 0
-
This operation displays the The

2.4:Operations on Array
2.3: Array Overview
Q.5 Write a Python program to insert an element in an array.
Q.4 Explain the types of arrays.
Ans.
Ans. One dimensional array
dimensional array 'a' is declared as int a[10]; Python Program
The one
elements are there in Aray?")
print("\nHow many
Value stored in array
n int(input())
10 array= l
20
Index i=0
used to find
the element 2 30 for i in range(n):
40 print("n Enter element in Array")
item int(input()
array.append(item)
want to insert an element")
print("Enter the location where you
position= int(input())
Twodimensional array print("Enter the value to insert")
If we declare a two dimensional array aS
value int(input())
int a[10] [3); array=arrayl:position]+|value]+araylposition:

pIcoDS A Guide for Engineering Students A Guide for Engineering Studen


QIcoDID
Linear Data Structur
2-4 using Sequential Organizan
Sructures
Linear Data Structure
Fundamentals
ofData Fundamentals of Data Structures 2-5 using Seguentlal Organlation

pnnt("Resultant array is\n")


print("Resultant aray is\n")
print(array)

array.
print(array)
traversal of an

Q.6 Explain the


2.5 Merging of Two Arrays
Ans. The for loop is
The loop is used in list for traversing purpose. Q.8 How to merge two arrays? Explain it with suitable example.
elements.
the list
traverse
Ans Merging of two arrays result into a single array in which elements

Syntax are arranged in sorted order.

VARIABLE in LIST For example -


Consider two arrays as follows
for
BODY Step 1
a1 a2
Example
>>>a=l'a', 'b','c','d','e'] # List a is created
10 30 50 70 20 40 60 80
> > for i in a:
Create empty resultant array named a3
print() a3
will result into

Step 2
a a2

20 4060 80 Compare a] and a


10 30 50 70 The lesser elementis
transferred to a3.

a3
a.7 Write a Python program to delete an element from an array.

Ans.: Python Program


10 k
print("\nHow many elements are there in Array?") Then increment i and k
As al[i] <
a2j], transfer element al[ijto a3[k].
n = int(input()
pointer
array = [1
Step 3
i=0
for i in range(n):
a1 a2 As Al is less
print("n Enter element in Amay")
10 30 50 70 20 40 60 80 than A transfer
i it to a3
item = int(input())

array.append(item)
print("Enter the index from where you want to delete
position int{input(0)
an element") 10 20
a3
array=arrayl:position] +arraylposition+1:] As a20] is transferred to a3 aray increment j and k pointer.

CIcoDD A Guide for A Guide for Engineering Sudents


Engineering Students QECOD

You might also like