1. elasSMA
C
Date
Page 1
imon Ansari 272
Space ime coOmpleai
Alorithnn:It is a proceolure to Solve
aproblenn io finite numbeu a
SHeps
Theue may
fo peufornming
Eq: Sorting.
be more Thon 1 olgorithm
he Same tesk
Hence,E
isnecebsau
which
Sitvatton.
Alqorithns OMe oUnalySeo
factor-Space
less Space thenits executom_tim0
to ole cicle
algorithm s bette in wuhich
with_2
tinneiit takes
is hiqheu
Geneually, time analys/'s
Ki S as qivenmon-
importance while hmakin9 COmparitjcn
of algorithna of SOme
2. ASSMAte
Date
Poge
Aiman Anari 272
Space CompCxily
f memony
f s is olefined os Ommovnt memony
mqveut an algorithm to run.
Space
2 factos Constant
uSing
Compleri s conmputed USin
charactoristfcs
iInstanCe characteristicg
S Ct Sp
C Constoant
Sp Voujable
Example 1:
for thisctaement
he Spa
ce req uirement
Sp
i s S C+Sp
Heue, Sp 0
9 C+0
Example. 2
SuUm 0
o r i 1 n
Sum Sum + ali]
reqviroment othis Statennent is
eqvired for
The Spate
1 unit Space
1 vnit Spate rvired
1 unit Space required
n vnitSpdce reqvied
Sum
o n
r an1
Thus, th total space reqviedd is Cn3)
3 = Cn+3)
3. elAsSMAte
Date
Page 3
AimanAnsari 272
*ASymptotio Notations
Asyneptotic AStraight Iine closely atpreaches
but nereu me by a C ve
Three asyntptolic notalions OMe uoeol 7o find
ime Complexi by.
iOmego
ii Thea Noteution (o)
ii Biq-OhNotaliom (o)
he
Natatien (2)
CBeot case Analysis)
iOmeqa Notatcn ():
giveo theminimum amoun oy time
algorithm neeola to un.
an
Let
Fln) and 9ln) be two non-
neqain
tundions.
no and c_be wo
jntegeLA Svch hoct
C>0.
no £ n
Then
and
Fn)2 c
9 Cn) for cau n2 no
Heue, Fn)is denote a CgCh))
The C Mwe netation is
Tn)
Fn)
Cagn)
Mo
4. elASSMAte
Date
Page
Aiman Ansari 2722
(Aveaga Case Analysin)
amovnt a ime an
i.ThetaNotedicrn (o)
J giA the areuage
algorithmn
Let
neeods.
FCn) and 9(n)_be twonon-negatie functions
C and cz aue wo postrvne constrcdints,
Svch that
C 9n) 5 Fn) s Cz 9(n)
Heue, Fn) solenoted os oCgh))
The cuve for nortalon is
Tn)
Cgln)
Fn)
C n
n
no
5. classmate
Date
Page
Aiman AnNari 272
i. Biq-Oh Notation (0) (werst Case gnalys)
qired he niaximunm Omovntoyie an
algorithn necels
Heue,
h) C 9(n)
Heue, Fln) Isdenoteol as olgtn2)
The CLMV for Big -Oh noteution
on_i's
Tn)
C qln)
Fn)
n
hs
While analyoing an algorithm, nly worst
Caseis Consideued.
The
the algoci'thm willlnot
than the
weret Ce onalysis9venuntees that
Lake mern tinne
Calculateo One.
Rules o
i Conutant eums
Biq Oh hatation
Oe expresse.ol cus olL).
eMeuy extLutable Qtcutenuent wi take
Unit cuout o nle, c9orellus o he
Si 2e o heolouta it
f o r Sone
pro ceAs es.
Conutnt C
OCc) oC1)
6. lASSMALe
Date
Page 6
Aiman Anan 272
a at5
This stalement reguins 2 time unit.
Secono for
ol2) = OC1)
One fur additon onol
je ol2
s siqnMent
i.Multiplicativ Constants 0re OMi tteol.
each ask nnsIn tinue
4 tasks will run in O(4), which
Sinnplie to Oln) ie. olcn)-c.0[n)
TOn)= n, thn
oln)
ii. Addtien s perfermeol
Maximum. e4:If 7 (n): n
by -oaking Meadume
Om ol
onc
Tn) n two
tasks to be executed seqventialy,then
he vebult is O(n)+oo')
on)
ie. olT): o(1) olT +T)
maxfof)sofr.)]
iv. Multiplicoction is use d when one task
Couuse Cnothon task tu be exeoiuted
Some numbers otimes for cach
e nedeol_loep
om).ofn) lmn)
cach
iegrotion fitsel.
7. elasSMAte
Data
Page
Aiman Anur 272
Exanmpleo
main C)
int a2
vnits
2 uniEs
1 adodiHon
1 assig nament
ot)to(2) of1t2)
ol2)
ol1)
main C)
int_i, n, aj
n 5
O 10
r i O; ien itt)l
t t
The progrona
execued
Time take
j:e 2unit
e 1vnit
n 5 once
exe cutec on
executed (ntl) time
(n times when the conditian
tnue onol 2 inne when
the conditon is olse )
i
J<n
iv. exe teel h times in 2n unib
V. tt exe cuteel n mes in 2n unibs
Totod ime taken by the program.
2n
1+1+(na
1) +n 2n
o (4n)
On)
ol3)
F
8. claSSMAte
Date
Page
Ainan Ansari 272
main C)2
int j.n, aj
ferCio ich_ itt)
fer lj:ojahjtt,
atEj
Total ime taken by 7he
+o+ 1) +n
prag ram
+n+ 1)+ht 2n
lvop (for) 2nd loup (tor) att
a>lo
= 2n 4n t5
0l2n)+ 40n) + o (5)
O(n) aln)+
0(1)
o(n2) oln)
on)
Thu fuc single r laop hime complexily_is
always0n)arnd or nested for loept,
time Compexi isalrays Oln)
Thw,
ol1)
0 (n)
0(n)
0Ln)
Constent Hme
time
Linem
qvaclrolic
Cvbic me
inne
o(log-) olalogn) -legarithm Hime.
9. elassmALe
Date
Pege
Aiman Ansori 272
Recuenceo
When an algorithm containsarecMrSire
Call,its running inne s_desCribed
by a e Currence egvation on recurrence
Mathe moutical tools are useol 7p olve
hese e curences
i. Subsituition Method
i. Kecursion Tme Method
ii Maoteu Yethod.
j. Substiturion
The Solution s 9vessed onol mathematica
incluctions vsed to prone that
esE9UASis Coe ct
tranaple 1:
Recumence rlation: Ttn) TCn-1) +
InitialCondition Tlo)= o
method:
he
o incoreet
Sal:
Il1) -[1-1)+1
T(O) +1
na1, then
O 1
T) =7(2-1) +12
T(1)+2
n:2,hen
Tn)
n
1 1+22
3 2 3
T(3) T (3-1) t 3
T(2) + 3
3+ 3
6
h 3,-Hhen
So on
6 T(n)n (nt1)
2
10. elAsSMALe
Date.
Page 10
Aiman Antari 272
Enampe 2:
Recurrence relatten T(n) =T (n-1) t1
Initialconolitions T(o) 0
n- then T() rl-1) 1
T lo)+1
1
h2, then Il) T(2-1) 1
T(1) 1
1+1
2
n-3, hen T(3)=T(3-1) +1
T(2) +1
2+ 1
1hvs
T
Tn) h
o (n)
2 2
3 3
i.Subrtitution method
We odrouw arecursion ree_ancl calculate
80 on.
by eveuy
the ime taken lerel of
the tree
inay, weSvn the work done
all he lerels.
lo drauw he recursion re,we start m
om
the gln rncurena relation anol kap
olrawo
levels Thispatteun tpically
olrauin4 lwe find a patteun among
a authmelic
On geometric Seuieo
11. elassmAte
Date
Page
Aiman Ansari 972
Example 1:
Kecurence
So
relaton: Tn): 27(h/2) +n
n h
(n/2 n/2 2nh=n
(n/4) (n/4) (n /4):: 4*nla n
n/8 (n/8) nl8 n/a hl8) (n/8 nl8) (nl8)8n/8=n
The depth a he ree islog n
nlo9
Hence,he total cosSt
onlo9n)
Example2 Tln) Tln/3) + 7m/a)+n
S
n 13 h/34 2n/3n
n/3
b/ (2n/9 (2n 1) 4n19 9n/n
hl27 2.,/222/2 Anl27) n274np) An/27 (8n/27
27n/27=n
he olepth
Hen ce, toteu_Cost
othe tree is Joq n
n lo9 n
on logn)
12. ASSMALe
Date
Page 12
Aiman Angari272
Cxample3: To). 3I(n/a,) tn.
Sol"
n
n/4) n/a) n/a)
bMs/1616
T[h) nt3h/4)+ aln/16)+
n 3 nt3n/4 t qn/16 +
n1+3/4 t9/16+ f
o (n)
Example4 Tn)»27(n/2) + n
n 2) n /2)
n14) a ) ) na)
1)Co/8
Tn)n?2(nl2) (n4)+
n 2n/4 + 4n /16
h2 1+ 2/44//6
n 1+ 2+ 1/4+
13. lAsSMAte
Date
Page 53
Aiman Anyari 272
Cxample 5:
T()3r(n/a) + cn
So1"
Cnia) na) a)
6A)otn)'(otn
rn)h' 3/n/) +9(nlue)*
n' 3n'/4 +
n'/16 p
n 1 t 3/4t 2/16_t
oln)
14. elASSMAte
Date
Page-
Aiman Ansari 272
ii Masteu MMethod
It s a direot
Souttcn.
way
to get he
Lwarts Gnyorthe
ruMHendLA
Mau method
ellow ing tpes
Tln) a (nlb)i FCn)
wheue a Sonstant and
az
nzd and disSame constant
FCn) must be positie
T(n) QT(n/b) +Elh)
ase 1 I Fn)is nwhere d20 hen
ia< ,To) =e(n)
b ia Tb) e(n logn2
C abTO) =_o(n'y)
Car 2 EC) s 'b then
T(n) (n'gb)
Cae 3 f Fln) is (n
To
log n)
n)
15. clASSMAe
Date
Page IS
Aiman Ansari 272
Excanaplel: Tn) 4T(nt2) tn
wWe han, Tln) al ln/b)+F(n)
Heue a:4, b2 Ond ECn)n lase1)
e n ,hente d:1
Now, 2 2
Thvs,a b
Tn)
/Case 1C]
OCleg)
Example 2: T(n) = 2T (n/2) +_blogn
Sal :
T (n) aT(nlb) F(n)
Heue
Heue, a 2 b 2 an FCo)nlogh lase3
T(h) nlosyb log n
Alow, ogb log2
lokt lo 141
2
.T(n) lg2 n
loq*
k+l
e (n log
O n lo9 h)
nample 3: Tn) 4T(n/2) tn2
Sol
Th)a7T(n/)+ Fh)
Heut, a 4, b9 and Pn) -n?lCase 11
ied-2
Nou),_b 2
Hene a:
b Tlase 1b7
T(a) o (n log n)
en lon)
16. AsSMAte
Dofe
Page16
Aiman Ansari 272
Example1 Tn)2T(n/2) tn
SoP:
Tn)a 7(n/b) tFn)
Heae oa= 2 b:2 anol Fn)=n flaoe 1]
ie d=3
Now, b =22
Heue a<b llase 1a ]
TCn) b')
= eln)
Example5 TCn) 2 T(n/2) t n
So)"
Tn) aT (nlb)tFln)
Heue a 2", b-2 and F(n) =
n°
ie d n
be Canstant
and bd shod
Hence, maoto
a
methOd is not
pplico be.
Example 6: Tn) 2T (n/a) tn°
Sol"
Heue, a 2
Now, b
a<b
b :a n d d 0:SL Case
2 03
Case 1a]
Ia) Cnrd)
17. Pge 7
iman Anori 272
Example 7: Tn) 0-5 T(n12) t 1/
1/n
Soth
Hene, a 05, b:2 and F Cn) / n
Since
Since, as1 , ma0tM Metho d not
ap
plicable.
Example &TCo)- 9r(n3) »'logn
Sal"
Hewe, a:9, b 3 and Eln) : 'bgnlase3]
TCn)=
=o(nagb
loq
lagkil_n)
log3
tth
lag
(n log
TCn)
Eomple : Tn)64T(n (8)-h'logh
Sol:
Hee, a: 64, b:8 and Fln).-h2 logn
Maste method is not appliceble sine FCn)
is negati n
Example 10: TCn 2T (n /2) tn
Sal":
Heue, a z2,b : 2 ano Cn) . h [Case1
): d 1
Alow, b 2 2
hus a b TCase 1b]
T(h) ( loq n)
(nlogn)
18. 18
Airnon Ansari 272
In selecttor Sort,the. Ourroluy interpretel
as diriclec into two ports
Sorbeopart
Unsocteol
Selectton sort
interpreted
In
pdct
Initioully,
The socBeol part sempty.
The vhrorted partsThe entire amy
The
neyey pass itemation)the clteat
(selecked) and
the etmost
elemen1 S FovholOut
it is Swappea
elemenb
Example
Initially
Enply
with
70 30 20
50 60 10 A0
70 30 20 50 6010 A0
Sorteol Uhsorteol
10 70 30 2050 60 0
Sortecl unSorted
10 20 70 30 $0 60 40
Soc ted
Unsorled
10 2030 70 S0 60 40
Sorteo
Un.Sorbed
19. ciassMAte
Aiman Ansari 272
10 20 30 0 70 50 60
Sorteol
Unsorted
0 20 30 40 50 70 6bo
Sorteo Unsorted
O 20 30 40 5O 60 7O
Sorteol Unsorteol
20 30 40 50 60 70 Sorteol
arrouy
Analysis ofSelection Soct
Heue, or Selecting
homthe
he Smalleotelement
Uhsarted parz equines
oll he 'nelements
SCanhing
. i e (n-1)COmparisdns
Findin9 the next Shmallest e
requires (h-2) CO p.arisons
elemeht
Ond So an
Thus,
Number Comparcons(h-)+
+[n-2) +.2 +1
nln-1) /2
oln)
Thus, he Complexitiy Selectton SOrt
is o(n)
Worst BeJt cnd Areuage Case
20. Paoe20
Aiman Ansari 272
Insertion Sort
In insertlon Sort the array
ioterpreteol
into two parts
Sorted porE
Unsortecl
is
as if isolividel
part
Initialy,
heSorteol part S emptiy
h e Unsorted port s 7he_entie
Orrou4
ln iosertion Sort, he eements
are inserted at
hence The name Insertion Sort
ereuypuSs
PcLSs (ituatian) on
element rom he hSarte.d
Their proper plare,
port
SinSemteol in he Sortcd port
appropricute place
Example: 30 70 20 50 40 10 60
Initially
Enopty 3070 20 S0 40 10 60
Sorted vneorteo
30 70 20 50 40 10 60
Sorteol unsarteol
30 70 20 50 40 10 60
SorEeel on
8ortte
21. elas5MAte.
Date
Page
Ariman Angari 272
20 30 70 9O 50 60
Sorteod Unsorteol
20 30 50 70 0 10 60
Sorted unsorteol
20 30 0 5O 70 O 60
Sor ted unsorte ol
O 20 30 40 So 70 60
9orted unsoreol
10 20 30 10 50 60 70 sartec
orra1
22. alAsshA
Dete
Pege 22
Aiman Ansari 272
Analysls ayinseytio 90rt:
worst
at it's
case, inserting he eleme
PropeM place will olo
oll n eehnenZs.
Scanning
-1)n-1) Comparisons
Findin9
reqvins In-2) CompaLisOnSancd
the hext 9mallea 2 element
SO On
Thus,
Numbe ocompalisons
(n-1) +2-2)t+2+1
hln-1)/2
0lb+)
This s the LwarS Case ond
Oveucge Case Complex
Bes Cose
When he aMucuy
In ereuy pais(itation), Single
Compouisans S hmoode.
Hence,
s alueadySored
the to tal humbey a
OMe n
lompoujsons
Thus, the tamplexil
s0/n)
in beot Cae
23. elassmae
Dake
Bege 23
Aiman Ansor 272
Complexit class
oC)
O(n)
atogn), on logn) etc
o(n)
o(n)
0(kh)
O(nl)
ime
Constan
Lineartime
Logarnthmic -ie
time
uadratic
Polynamial
Exponential time
Factorial
ime
Hme
wheue,
k constant and
n s he input sizee
P,NP NP-Complete NPHard Prablems
NP-Had Hordeat
P
Hard Medivnm NP
Hard
NP-Complete
NP--
Cornplete
NP Medium Hardeat NP-
P
Hard
taay
24. acsmate
pote94.
Fege2
Aiman Ansari 272
*|P Class of Problemc
P-Polynomioud i e Solving
s Se Problenos
9olveo
that
in polynomic
Qun be
time
P hke O(b),
proble m take 1inne
0ln). 0(n)
Exaople: inding marimum clement
in onOrray or to check.whetber
aSting s palindrame Or not
a Problemd
Non-deerministic fblynomial tinme
Saluing
NP Class
NP
It ic a et_opcoblemAthat cant
be Saveel
Example Sum o Svlbset Given0
Palynonmial time
Set umbeuS, doeo tbeue exis|
whose SumszeMo2
Subset
NP pabems OMe cbeckable in
NP
palynamial ime
ie.given a Solutton
we Can Check thot
Solutio
palynomial ime
o_aprablena,
whetheu the
S COrre.ct on not i
25. efasSMAte
( Dole
925S
Aimon nsari 272
NP- Hard
Re olucbili
7oke two problemg AOnol B. Both Or
and NP- (omp lere Proble ms :
wo
NP prsblem
we Can Convert
Q problem
Emeans hat A iseducible to B
NP- Hard: If _we fovnol hatA is
reolucible o B hen i2_meanA hat
Bis
insance
A )otoprebem B, he
One
to B
ctleas as
NP Complete: 7he
which a
harola20 A
grovp a prObehoS
both Jn NP anol NP-hard
known a NP-Conmplete probbm
ar
99. classmat
Date
Module 2: Divide 1Conever Approach
Pege26
n this approach, the problem sdiride l
jnto SmolleP4 Sub-prablems and then
ea ch Sub-problem is solved indeperdently.
The Solution of allsubproblems S
inally merqeol to abtain The olutiun
of the Origina peb lem.
a b e problemn
Divide a b C e
Svbproblem
Conqier A D E
svbsoluton
a b e 9olutlon
Divide This step breaks he problem into
Sub-problerns.
3maller
Solvesa lotof Smaler
Subproblems , #0 get Sub-Solution
angver: hisStep
Merge This step
the
inodSolui'on.
recursively Combinea au
Hhe
gub-Soluian to get
ger
DSE2O Aiman Ansari
-
100. elsssate
( 27
Pege
Airan Anar DSE20 (272)
Merge Sort
Merge ort vses divide ond conquer
gtrategyy
Consists
Divide
ot 3Seps
Divide4 hearrayinto
2 elerments
Sub-arrouys with_ 2elernents
ii) Congver: Sort the two
Sub-arrou
in)Combine:Merge the two sub-aro
into a Sinqle orteol Orouy
Example
L18 2 o Is12 aIS6
Divide
LBl 2 ol15
pi
Divide IS 6
pass2 18
Dividle
poss3
Divide
pogs 4
Nupe
pat 5 9 12 6I5
Merg
purd6 6 912 Is
Mrge
paus 7
o 211is1 6912s
Nerge
LO216 112 1S 51
Numbe0pa n-1
ps&
101. efasata
2
Aiman Anrori 272
Algor1thm
A1n]is the arrauy to be sorte
MergesortC) sthe onction which
for he merge Sort
Sar
ted
to
IS
e-ettene recursiveuy Caleokto
divide he
CombineC) isthe-funcHonn
Sartsand then m egea he diridec
array
array
whichb
meygeSort (AJ1n low, high)
if Clow high)
mid Clow 1hiqh)/2
meugeSort (A, low, high)
meuge Sort (A, mid 1, high)
meuge Sort (A, low, high)j
3
Analysis 0f mexge Sort
Let T(n) be the ime required by nmerge Sort
to Soct n_eleroen
Then TCn) 2T(n/2)+ n
Mast Methoc
Now, Veing
we hae Tn) aT(/b))+F(n)
a 2, b 2 and FCn) nwheue d 1.Case1|
b 2 2
. .
LCase 1b1
Thu, T(n) o (n"loqo)
0nlogn))
102. cfASSMAte
Dote
Page29
AimanAntari 272
Combine (Al1.n]
n],low, mld, high)
k i lawj
midt1
while Lis:mid &d jsehigh){
ifALI] <e AljI)
templk] Alil
+t
J else
temp Lk] ALjl
k 4t
while Cir mid)
tempLk] : Alil
k+
while (j< mhigh) {
tomp [k] ALjl
ktt)
tork: louw k<=high k t )
ALrJ = tenap lr];
103. elassMAte
Dote
30
Page
Aiman Prngari 272
Quick Sort
Quick Sort vseo olivide canqve
Strate99
Quick Cort
Divide Diride he arrouy into 2 sub-
Cons)s 1s of thepe Seps
array Svch hat each element
is
eft sub-arnoy
lessthan or
cgua to the
in hhe
Cncl ea ch
middlle
element in the rlght Sub-
arrouyis9reatou han
mldodle
oivisian is based
element
The
elemert Th/s
On pirat
eAement
i)Conqve hecurssively Sor
Sub-auay
ii)Combine Lonbineoau theorteol
the 2
Svb-ar ra
arroy
into a Single
Sorteolelements.
aivisian is based
of
Soct, the division
actvo value
In meuge art, he
pociions
On the arrouuy elements
wheueas in qvick
of he
bosed on
element.
104. cassmate
Date
Page31
Aiman Anari 212
Algurithnm or Quick Sort
quickort_(Alz..n], hrst, last)
C i r s t < l o s t ) i
pivot first
first
last
while (isj)f
while(Ai]<:AlpiratJLk i s las)
it J
while (AljjèAlprvet]k4 j2irst)f
if
tennp Alil
Ali) Ajl
Aljl temp
3
temp
Alpivot
Al] temp
Alpivat 1
Aljl;
qvickSortA, Arst, ji-1)i
gvickSort (A, JA1, last)j
105. alssmate
Date
Puge 32
Aiman Rnaari 272
Pnalysis of Quick Sort
Yorst Case
hlost Case
elements
OCCure when the key
9e placed
O oy Size
CAt One end
and he
In 2 pass, he key 9ets plarel
is (n-1-1parr
one end and Si2e
(n-2) remainA, andSo on
Hence, 7he to tal
CompauiSions to
numbeu
Sort he Cumple te
(n-1+ (h-2)
nin-V2
2 1
0:5n - 0:5n
0 Sn
Oln)
Best Cale
he array 1s aluway
ot he mid henhe
gires the beat
Partiioned
olgorithm
Cose effeciency
LDeuivotlan ic Sanme as thad o meuge Jort
Thus, he comple.xiy02vick Sort is
Beat Case
Aveage Case
Worst Case
o ln logn)
Onlog)
O C n n
108. elasSMALe
Date
Page 35S
Ainan Antaui 272
Univeusity Queation
E, X A,M, P L,E
A M P L E
pivot
ijSwop
Ali)_ond Aljl
P L
E E A
pivet
E E P X
M
pivat
i j Swaplj] and Alpivet]
E M P
E
pivet pvot
E
A
pivet
P
E Pivet X
SwapAlpiret and alj]
pivet
Swapiand Alil
A E P
pivet
SwapAlpivel and Aljl
A E L M
pivot
A E E M P
L
pivrt
Sup Alplvot]_ond Al
AE E M
L P X
109. elASSMAte
Date
Poge 36
imanAnsuri272
Pinding minimunm
min and max
Onol moarimumi
valuea from an
Using-
armoy Can be founod
mar main (A (n), m ar, min) L
max min A [O]
for (i 1
to n i
if ACi) > mar)
ma Alil
i
ALi] < min) }
min A i]
J
Nomber of cumpauisons = 2 (n-1)
This min Qnd max vou
e can be fovnol
recuSive method.
vsing
The methocl vses divide
Strategy
e cuSive
and
The numbe o Compaulsicns heue
ConqueL
3 /2- 1
the mlcddle
trom his
minimum elemenk oe
he list o elements i divideol out
to 9er
Sub-qray ma ximunm
two Sub -arrouy8
and
S elecred.
This proress S Carried out foc he
entir arroy
110. elasSMAte
Date
Page 37
Aiman Anori 272
Algorithm
maxmin li,J
ili:j)
mar min:AlIJ
Jelse
i
i lAi] A lj])
max AGI
min A(iJ
else
Alil
min Alj
mar
3else i
mid (itj) 2
maxmin imia) /cc
new h20x max
new n in min
moaxmin (midt1,jj
ifmax newmar){
mor = newmax
Jif min newmin)
min newmin
111. elassmate
Date
Page 383
Aiman Ansari 272
oExample
20 10-4-21s50 45 Is 40
20L1o1l-zlis 50 151540
2010- -81s 50S 1s0
may:S mar: 550
Eelrol
max 46
min s8 min: 4S min / 5
max 20 max -
min: I0
min:-1 max 50
min IS
n o r 20
min: -4
mox 20
min -6
mar 50
min -8
Analysis
For each half divided svb-arrmy, theue are
two reCursiveCalls made.
Hence, time required r conoprting
T[n) 27 n/2) 2c
2 0n/2) 2 olc)
o (n/2) o (c)
o (n/2)
to Combine
=On)
Thua, he ime Complexity 1S O(n).
Thud
182. Date
Page 39
AimanAnsari 272
o Binary Search
The elemeniS in the array should_be
in SOrtcol orcleu
The elemer _be Searched is ooled
he KEY e men
Let ALm] be he midolle elemeni
ua4- A
key
key=_Alm], then he dedinedelenment
spreaent_in he Cirroy-
le-t
1 key <_AlM), then secrch The
Subarr
key > Alm] then searCh the right
Subarrog
CuLOLy ls cliricdeo
he name binany-
Duringthe Search
into two
8Carch
Example
11 33 37 2 45
parbs hence
9 100
Let the elemen to be searcheol
Find the midde elemen in he array
it with 99
ancd CompauAe
11 3337 42 4S 29 100
lesubauu Middle
element
right SVb -Qwua
183. elASSMAte
Date
Page 4o
Aiman Ansari- 272
Since 97 z42, the righ Svb-auy iS
searched.
45 IO0
middle eleme Elemcn founa)
Anclysis 0 Binouy Search
binauyeareh(alLw], element)
irstO
last n-1
whiletirsb <= last) i
mid(tirst +las?)/z
i elemen a[mid1)
break
else i
element almid))
break
eAse
irst midt1
i irst last)
Print ( Elemeni nav tound")
else
print(Element -found)
184. IASSMALe
Date
Page 41
Aiman Ansari -272
Analysrs o Binary Search
Bes Case
The element to be SearcheelISpreent
The preentt
pocisio0 ThuA, it
irst Search
is
in middle
tound in
Hence he searching ime 1S
indepen dent cf henumber o
elemens in he CArro
Worst Case
The to be senrcheel is
elerment
PyebenL
Or ib is presenL et the enc
CUMo when Cnly
eitheua no int h e array
op the o n
elemeNt remains
For example, isize o he Carrouy
is 256 hen he Searching
Cohtinues with redluue ed `ze o
256 128 6 32 16 8 2 1
6
. Nurmbe osearched
J09, 256
thud n wors Caoe
i ollogn)
no. oSearche
185. elassMAte
Date
Page C
42
Aiman Ansari- 272
AveMage Case:
On nunmbeu of searcheo LS
2logn
o(logn)
=
Camplexitieo O al divide and Conqueu
algarithms:
Algonthm Bebt(au0e Avq Case Worstare
MeryeSer1
GuickSar
Min Nax Alg
BinarrSearch
O(nlogn)
Ofnlogn)
Oln)
o(1)
Olnlogn)
Onlogn)
Oln)
oflogn)
Dnogn)
Oln)
olD)
O(logn)
186. ASSMALe
Date
Page 43
Ainan 272
Macdule 3: Medy Method Approach
eneucl Method
Geecdy methols aue uoed-Jor obtaining
optiized Solutions.
An optimizedSotchiorn is the beat
Svluction
Aqrecdy algorithrm a0 he
SVggests, always makes the Choicehat
hame
besb al that
Seem& o be he
mamcni
Urtedy methoodperformA he ollowina
activihics
iSonne Soluian js Selkcted trom the
inpu domairn
ii. Theniischecked whetheu the
Solutian isfeasibk or no
ii. From the Sec feasible olutionA,
hadSactistieo
pauticukau Solution
o he neauly
neaulySotifiea
Satistie he
Or
objccties is ectisied
Sele cteo
Ln_oreecly methoc, we attempDt to
Constut CAn Opimal_Solllon in
Stageo.
At each gtage, we
deasion Th appear be
ho ime
make CCicgrana-
best at
A deis ian once made
not changed in a
each deiSion Should
Cut Ohe tage S
latey tage. So
oASure easibility
187. elassM
Date.
Page
Airnan Ansani 272
Thus
At eCh Slep, a
beDt_choice is na de
NexeM backtrack nor change the past
choiceo
Neveu lookahead to SeeiCurrent
deeision wolol hare any hegati
impactio fucdur.
Single Source Shorteot path
(Dijkstra[ Algorithm)
geneuay a
graph s Used to
represcs
the disance between pwo Citeo.
to tind aPath from One city 7D
lhe Simple OurceShortcot Path s Used
anctheu
The
atria vector callecl Source, 7o all
he
city qvickly
ghortot distance trom a Single
Otheu veuices is Obtained.
oblem stautement
iven a guaph and a Sowue veuter
in the gaph,indThe shorlest
he Veute
pathsfrom he
to aU
SOLuCce
otheu Veutice in the given
guaph.
188. SMALe
Date
Pege s
Aiman Ansari 272
Algorithmn
dijkstro lg, w, s) {
initializeSingle-Source (g,s)
9 v
while
U extract-inq)
S S uu
-tor each veutexv E G Adjfu
relax (u, V,w)
Analys is
Thetime
Alqonithm dependo on the wra
he minimun
implementeo
The
a Dijkstra's
woS
Complexily
how
priori 2Ueue
y2
Complexi is02) furnarmal
the priory qveue isimplementol
heap
VSing binauy heap
Complexily s
then he
of logr)
193. alAsSMAte
Date
SO
Page
Aiman Ansari 272
example 4
Step1: VeuBer A Step2: Vertex D
7/p 1/D
B
s/p
Shp 3 Veutex E Step 4 Veutex B
7/D 1/D 7/D 9/B
B
3 3
stb
3/A
7/0
Step 5 :Veutex C /8
s/p
3/A
194. Dote
poge SL
Aiman Andaui 272
2
Exarmple 4
Step 1: Veutx 9
2/a
Is/a
Step 2: Veuttx b
2/a
2/4a
Step 3: Veutex e
2/4
3
5/5/b
12/a
Step 1: Veutex C
2/4
3
5/5/b
a) n/c
6/a