0% found this document useful (0 votes)
46 views41 pages

Data Structures UNIT-1

The document discusses different data structures including primitive and non-primitive structures. It describes common data structures like arrays, stacks, queues, linked lists, trees and graphs. It explains the features and limitations of arrays and advantages of linked lists.

Uploaded by

mcuthor98
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views41 pages

Data Structures UNIT-1

The document discusses different data structures including primitive and non-primitive structures. It describes common data structures like arrays, stacks, queues, linked lists, trees and graphs. It explains the features and limitations of arrays and advantages of linked lists.

Uploaded by

mcuthor98
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Dat Stuctunes

ha Study of data stvuctune heos y, you to undesemd


has dat s ongumized and
omd ha dota flo is
to
proyam.
Dat1 shucne is the stuchusa eprenthon &
Jogic nlotionhip behwen daa elements This merms
a deta soucheri onecai zes
7e lata ilems baed on the
nolahonship bohseen tnho date elementy.
Data etuchue is a structed cetvaniase thad
cue nll to ench ohea Lwhich fon the baic Componeit

Boic Tenmindkos blocks amg pnogm


Deta stuctwes bulding
a an vole
elementany vaue
doned
Douty Ootu Coun be Vey for example, shucents
on the collection deta obout the sudet.
Cnd ik id ade the Sordnoe det
Tems Det tems hich have
Uioup hroup tems,tov example, hame
tems ue coled Bo cnd he at n
irst name
t ashudent can hawe calecton od
Racond Can be dhned a the about
Recone examle,t we tlle
Vanious data iems forit name,addhs,loae and an manly
studed entit then cordfor the shudet.
the toyen to fom the ne
an he oroupelacoecfion Vanioy necands one tyee g
Fle- AAl is amoey stuants
entihy For erampleit tene an bo elted
be oaloves in the
nthe cles, thon the wll data abat ench
ecord Boty the
FNe Uhee ench
emyee.
Atibute amd emtithy:- An enhity nepents the clas o
objects, it Contan voiouy ottibtes. Gach attribute
Certuin
supraeti the ponticakan propcty f thet entity
Reld:- Rield is ashgle elemanty unit f ingomain
sapranendng the afibute of antentiy.
Need or Deta Structue oncoizoton olota.
ovel
’I4 Nes di/feronddata Cen be stonad md accaued in sts
’4 Aells ho
elementany Jevel data, Such as adg
’Pravide opakon on jtem.
tem, ookng up thihet pnionity amunt f olata
’ Pravide a meansto menaye hugé
hue
efticienty.
Sanhny of ata.
’ Pravicle foud Seonchng cend sating
Chocds Data Statune
shruchue bauically implemants tado Conplmonty
Data
oals
Conacnes: Data stsmctne ¬sis deigme such thesd t
opertes Corecty forol knds f input, which is baec
On the domoin idaret. Tn othe wards,Canectnes
ulms tha primany yol lata stucune, which odays
depends on the spectic palemy that the clate
Structu is intendod to sove.
E4iieney: Duda sruchere alo neadsto becient.
I4 shol pnoces the datu od high sped whaut
udilizng much d the Comput eounces uch as memory
Spaa tn a rel'ima te the afticienay of a data
Struchene is an impantendt facton thet dteimihs dhe
Sucen ond faile of the procas.
Featunes ef Oata Stuctre wrsh
henenlyal compt prorammen
Robuumes: that oenenetes conact outpt
to praduce sofhuea t,as well as estace
pouiale inpt praviled to Thx kind
kind f but
o
exny hidwane plet fons
on al
manat both valid and
Sofwane mut be able to
Jmvalid input. prijecks uch as wand
Dawelapny eolfhsane Seanch emgne,
Adophability:We browse and thedcnle an exéute
procehons. Intenet
coae sytemy yeas. Maneover,
inwolwes Aenye or many menkat Condihsy
Connety cund due to evea chameng
SoAwane evowes Jechndayies
emenging amdaatabiliby go thamd-inhan
Rawsailihy: Rousaoility programmn neyines many
the an
It s a knon fect that
cofthiae, Which malees
for develong cmy cotwane is'dlevelpel
eouce
entrprise. Hswa,'hethen t can he
expenwe
neusale omd adaptable ay. apicotins.Thuy
impemened in most ef theftne sthuctnes, tis pastibde
implomnentny galdy dita
Da davelop sawsable sohwene, which temds to he cort
to
efoectve cmd tme Saw my
Duta Stuchues
asucdunee t of
o vaniabley
Adeta sructnes prvides in
that a awciatod with eech ohe eprelsts
bais d proanammng toal thed
I! forms a y det elements and halos
the nlationhip behwen
proerammens to prolens the olata eaily.
Data sduchune cem be clauitied into two Categanie:
OPaimitve deta structne
( Non-primitve data structere

Dota Struchue

Non- Pimitve
Primitve Datu structue
Structine

chaade Boaten

Non-Linean
Deta
Linen a Struetune
Structne
Areys
Taees
stachs
Canphs
Quaues
Paiitve Deta Stucune numhey andthe
uctne Conist of tha
Priie dete str
chanactes Lohich cne uit n pramg. Thee con be
operted direchy by the machne level
mamiplted on nten,net chuacten
instuctian. Baic dete type Seh as
omd Booleam Come undenpmite det stuctwes. Thee
data tyees Oue alo knon a imyple daty types
belauethay conwist of chenacens that connot be
dinded.
Von- pimitNe Deta svucte deved
data s dructe cune
eue those tht ae
Non-pimitve suctwe, Camnst
Strutues. Thee data
trom primitve date divety bg he machine lave En

opeatad on manipulsted
focws on fomotion a cet hate
nauctiows. homaenocs (Sam deetu tye)
element thots eithe tyee)amd noninen
n hateronsous (olibenand dat
fnthe dlvidod to ineon
Thee an gruche amd anamgemet
dota stuchne bued on the
neen Deta ructue
that maintouhy uinean
u nelaionhyg
Adeete struchne called a linen detu structue
among s element is tauhion. But in the
Heu, the data is unamged n a dinean
nend may nat he sequential.
memory the onangemend moy
Ex: Avtys, lintedlist,stacks,queves
rNon-inean Dost stucne
Non-inen data shuchue is a kin deta structue
n which data elomens ane not aanged in a Cegenkd
ondes Thereis a hienachicol nlsthionhip between
individut dacta items. tee,the inerton amd deleton
data s not poMible in a lineen fahion. Trees ane
oiaphs esamples f noninen data stchry.

frrag,in gonend, naje to am onyamgemed f


data elemgent. Arey is a tye datu shucture hat
Stanes data eloment,°in adiaant docottons. Arroy is
Cowidead ay nan dota structue thot oeeun Sarey
olemant of
b Some
Some data ype Hence t alo Catled os a
inean homoamoly
when we deleno CNay weakin initial
we ccUn
Valuesto each d is eloments by enclong the values
in haces S3.
int Num 's]-SR,7,67, So, 663) Shown bela:
This declaion will cneate am May
anay as
3

buces S3 shald be
mumhe f Vades idelemet that we dacle
The the numhe he
Eyual to bnactets
ünice he Squaredeclared S element
cas Pal,we have bnaces 3S
of
écumple i i i i l vaus within Aften
cnd in te for each elomend.
Cnel vales, one toy
one
we have Speat;e s Paual will hove fve inteyey y
this decJartion,a y intializtion valws.
we hawe erovided's
Coun be aiied Cu onedimonion aay,
aay
two-dimnionl auay on ulticimeniona
One-imansion Aryay:T4 has delmt
Tt as stened in asendng sdarane Joation.
Two-dimemion Arry:TA Conist f muttiple nos
as
amd adumns of data element. IH is aluo alled
matiX
Mudtidimonionl Arays: mhclimeniond anay Con
ag. thdimenioned
lae dened
are not boendod to two inices en two
dimamiony. They Cen incude as mony inicas ay
Jeqied.
LimtaonAays ane f AxeJ ize.
’ Dataelemeti sdone in Contgoas memoy
Lootion Lohich moy not be al available
’ Ingetin amd dolehin element Cam be robemk
beloue f shigng f lement from theiv
poition.
Haseve,thee limitotians Cam he colwl by uuny
inked ist:
Aeelcotians
’ stonina ist d daa elamats balongmm to Same
uciiny stoasg ton the data shvuchnes
>Shunay binan tee elemady ed Axed Coet
Shanage od maties
I Linked List
A Lineed ist is a data stYuchaein which each dat
elemant Contein apointu on lin tothe next element
an the ist. Thoush Lineud ist inion and eleon a
the data elemend poseibla at all lacey d a linean ist
Aoin
Also inLinked lit, it 4s not nacersany dhohave the data
elenamt stonad in consectve Locotiong. TH loctes Space
Fov eachn dtatem inits own lock od Thus,
a ined istis Coideed memory
as a chain 'eta elemest
Necovds Called odes. Each nodein theist Contain
anjormaton eld on a pointa Aeld The ntoation
feld Contansthe actual dt cnd the poita feld Contais
aoes o the ebsagued nodes in the ist.
vocles

Tnfaimih pant Next paint Rell


Anodes. Each
Hoove iene nopneret oa iadstthe wth ode Jepents he
nocde has two pd. The lalt pant in
paud sieh Contams an entine nlovd f oata items
ngmaton the nat node.
Cmd ha siht pont e t s the entn to
The pointn o he lout node Containy a ul pointa
Hdwentage: Eaien do imet ondelte deta elemads.
isocvanteug: slow seareh openation andngines role momary
spale.
Apeicatiows : drees ane
Inplemanting steks (ques,binany
oyphs o paded siz.
’mplement duynamic meny mamagmed
fencins opnotmg
’Palunonho meenn Sytom Ry mothemaic opst
’Cvlen anced ist is ed toimplement os an
appicin functions tht eqire saend Yobin
ececution odths.
Circuln ind ist s wed ina aide sho
’ ao back to the first slide
Jhen awn sants to
oten Jout slide Js displayed inthe ümelemendoton
youhly ined ist s ed ttoy in a browren
fovwond cnd buchwand
tornove bacewnds amdl to Lwene in the opemel
Palaus of a bwebite.
Civulan gueue is ued do maindaih the playng
Seguence f multiple ployos inagame
)Stacks in which incetion
lineen olece structune which
Astack elemands ane cone ot ony One end, lat-i
s a
amd deletiom od Suck is caled a
s lenown as tho top o he stack. elemedt which
Struce becawe the dat
Pvst-out IFo) clhrk is tho Avet elomod which is
is addod to the
dolated Aom the shack.
Top FF
EE
DD

AA

Bottom
Gem be smplometed
Compute's manuscles Se hematie slach
Jn the anays on Linked ss . iyue is a top od the
dng element aa is the
Here, Elemmot are
diagnam da stack.is the botom o tho tack.
amd elemend AA
top. Snce A follos IFO
frorm the doletel, and
added to tha stack be doleted holere FF Js
Podten, EE Cannt delehed bebre EE Jsis delek
Simila DD Camnat be
and o on
operston
Apeicaians: struchune ten Jacuave
’ Temporarg stonag! for natad opetioms, fenchi
’Auidny sarage soructneAumions
Callsdeleined(pestond
"Function clls eprenions nn Vanjous
’Mamag
’Evolotion d anihmate
Joumguae nto poslk eaplati
Progiammng, erprenions
7ConNeion iny erpreins in a proynamnang
’chocng Syntxo
envivonmand:
Matching panendheis
on backtaclny
pnbemy soutions tree owesc
- In al the Seareh in aph and
-7Usedin depth rst
Opewtmg
’ UNOO Sytamfnctions §n cm editon.
Anctons in
y and REDO

vueues datu strucue in


fvst-in, rst-od (FIFo)
queueis a ineeted ivst is he vst one
A a

element thd is acloled


which ho ot. The elemants na from the
to be tatcon amdemaved
emd calecl the en stacle queues Can be
at one
6t ealled te ot. ike nked ists.
otha end cusy on
implemanted by wng either elemets, where
qeue with 4
with 4
shos
shs a
a queue
Below Fze lemed nd 6s s the rean elemed
tront
omd doletel
SS is the he
Flemont Con he adoled Aom
Aom heont.

SS 22

qpeatin inraphs.
Appiations uedin breadth search prid bullen
’ 4is oeations of os Like a the
stare
’ Jdo shaduley
keyband butfei queue to
qeu, by wwes
Kays prened Disk

sehedudnd
’ Prierity eues eneued nAde donndng
coperstions in a brose.
’ Docta trenten boteen peiphenl olevicey ad
cPU:
’ Lnteupts genented by the wien apphatong
yCals handled by he customeny in BPO.
vJTrees shructo jn which date
ee js a noninean dety tee
A The data elaments in
bvanches. hieraschidsutu
S ongenizel in imposeya
CMamged ina sasted onden. I!
On the data elements coist ?nas.
atree which
Below Hyure sapneent, Go ot the top. Noce 24
oot af the tee is the node The nodes 6, 4, (2
The he hode Go.
dhe SuccoKols od thoy do not hawe cny
dhe temind noley a
amd 67 ane
Succeons.

int and delete opeutone.


Provide quc Seanch,
Adharge algoihn
Disalwantasg:Comicted doletion
hienachid struchuo in Compten
Implemenhng dhe
Juke dreckoy soructue of e webita
’Tmplemntg the nawigohion
Hifman's Code.
’ Cade aprehn Jake aplictiny
Lmlomonttion functins
piautyqeuas
os scheulny stelemonts in proammn
’ Pascmey d esreiony and
Janguge bomfles.
dota leys or DBms fan ndesang.
(2)
’Spamnng rees tor Nouhng decisons ncompuand
Commumicadiony notwonles.

alyonihm do imelemed in A1, nobies


’path.fndng
amd video Games applcoions.
V nnophy atee
noninen data structe.In
Aeraph is alo a in deynik
dodi shuchne,all data elomets ane shanadnade has ony
"hieranchicl stvuchue. In othn Lwonds,eachdota elemet
nade. while in eraphs, eoch oher
is cled a vetex end andls Connecte o mamy
Vetexes thuh Connectiany caled edyes.
conided y a mathemaha structue
Thus, aerph s Vertexe ameda set f eds.
which sComposed of aaset e nodes A, B,(,D,E, Famd
Hgue shaJS aqrnph with ix BI,3,[o,FJ amd DE
Sovon edyes a,6], CaJ,P],

E
Nales situatiany
made odwanle
Hdvantang: Bet
Dsadvanty:Some alyonhmy slaw and vey Complex.
ppltson:Reprethy natwoley ond notey in Commnicatig
tiampentthn ond drovel applictions
and othe ntuok-baed
natwoly
IntaGonmectony in Socid
>Applstiy.
Mapping appiatony wen prento.
pplsions to preend
prdlems Doted to
Ecomen ce
netwole to idontity the
’ Utlity Load Conponaobihty
municfed onwslzton amd ploy Cannechvit,
’y Rarowce mop ad a webit do ds
Dacemety Lmka hypaln ks
batueen ponyes hnaugh
newral metwovly
Rdotic moion
dat Shructue
structne vs Oyramic
Staie deta aunel onganinng dota
stretwe is a way d sdonin on them Con
on
Oota ogined openadiony
Guch chot the to time as wellay
elficed wth nee neduce
be Royomad be cn wed to
Dada Structne
momongSinmpy Ahe time Complexity ) the Cade.
Condaiy (mesity two types
Dota Strucne Can be
static Data strucne
O Sructue
Dota
3) Dynomic ghructue 2 sdructneis tixed
Datu
what is a steudic the size ed the but
dota strudwe be modifed
In atic soructueCan alloctedd toit
Content d the data
The the momory Space
wthod chamgn

2 3 4 S

Arrag
Frst indax =0
Lat index =
Dode sructues: Avrag
Example d shatic Doda
(12)
Data Stuctre' hot
whed is Dynamie Stuctue ig
&tructune the size e the penfomel
InI Dynamic dot madifed dusng the oprtons
deigedto kaciitote
Fixedand Con be shrchue aue
On it Oyamics clat
tho n time.
Change o det shuctues in
Mead
Dcta Next
Linked L!.
Dunamte Date Structne
tatie Data Structune vs Dy size whereoy
Staie Dota gtiuctne -has tixed memory
sie can be amdomly
in Dgnami Date stuctne,he
be Coniden
vpdla duny thich may
mime cole.
fha
to momory
ficied wth npedprovices anplenty aces to
mone eoie
Staic Dot Shructe to dynaic olet structe. Unlilee
elements wih epect hamic dade suctres
Static dat structures, dy
Openatony on Dal Structues em exackley
meany to aclexs each dat
havetg: I4 eoample, to prnd
ba proceMed. För
Once soicd it can Sucorsn a clas.
e al tho
we to nd the Loctioy ef one on mare
Searchne:H s Conehat. Such a ot
dat tms thot adisy tho gren
be posent intho gven collectio
Hem mayon may ut fall tha
o data ems Fo exampls, to nd ho mames
sudonts Who Secune loo muks h mofhemoes.
Tnentg: I+ is ued to cdmes dota itemy to the given
Lis oaa items. Far eaumple, to dd he details o a new
Stydend whohas neconly joined the Couse.
(1S
Doletmg:-TH meny to emove Cdelote) a pantculon dety
collecbion d deta iHerns. or ecample
jtem from dhe qem the Couse.
a stclent who has lof
todalode the nane
items Cam be ouhcmged n some, oneen
Sontng:- Dota descendang onde depenng
Ailce asconding onde on descomdng
eseemmple,amongng Calclotng
nme

the tyee o opplicton. For alphaastial ondon, &n


studerdt in a clts in am
thu peuteipams Soves
oinnens by a amghg he
the top thee wnnos edachny
hem eidachng the top Thee.
onden ad
ndescemding onde and thon combsned
Gorted data dems Con be
1/lngong:- Lat of two

ABsTRAT DATA TYPE


Tnstitate stomdand
stomdand omdTechnl
ond
Accon to otiondl f info modion, uylliy
tucture is cn CNg ani2don o Dta gruchur
CNs),a dati ficjencg.
btter alganhm ad hees.
The momoty for
inunclude staces Lnkacl List diction ay
queue, entidy,Suchashe name
oleobebe aa Corceptual
They Could clo
amd adoes o a peson. clen thet the opertons
Eom the above delinitn, is
invowehighonlevel abdachovy uch as
n dod sruchuo a List
dit acenng he hihet
addmg on dolamg aanist, idom on a
sastng am ifem
temn or Beanchany and
priony data dructe oey uch opetion it
n a Aist. twhon dhe
is clad an abetot data tye. data items doyedhen
cllection
IICan bedofnadon tho data.The cSarel "abtacd " oers
wth the operodins bac operotiong defre
tho data and the
to dho act thotstdied independontly od how they înplemnte
On it cne beme
I involwes hat Cam be dons wth the ooe, od howha
to be one. ar ex, in tho bolow ig-the weer c Dulel be
involwedin checky thad wnod Cam be done wth he clota
Colocte nol hos Hthay to be done.
Structuney to
anplomentaden of ADT Conis o
Stone the dat tem ond alanh uon bovic opertn. A
he data tructne, i: e anamad Lst, stak, qee ete
as examyples o AT.
A0T
Jn Ahe eal world, prosromy evolve a e o naw

Teinements on Conehaint,so a mai cotion to a proynam


Commonly seqines achange in one on mmone o s clata
Sucas for excmeei you wend to clel naw triell
-to ushelonts necovd to koptack of mone inomsdn obaut
anc a y cwth
each stdand henit will be betten toeplact
aIn ined
uch
shructune oîmprove the prognam' efpieng
a Scehanio, heitng eveny procedune that
uies the chamacd sdruchue is nt dermoble. Thenjae, a
botten altentveis to sopanste the ue o a clat sudure
Ham ho details od s implambndodion. This t the pinciple
abibract dete tyyles
undedying
ALGORTTHM
lwhich defhesa
step-by-Step procedune,
Algonthn is ato beexecaited ina Crtah oneler to yet
Sel dnstrucdions genenlly eneted
ho doined autpd. Alyonithm
cndepondad omguog, ie algonthm
Con be imlámended jnn mono h n ohe prayrmiing
(17)
Fxom dhe det guctue
dmpontant catagonies alyai ims:
semch am item inaclota struchue.
Seanch- Akyonhmto centan cnde,
Sond-Algonithto sotiemy in a
to inent item in a dat structre
-7Tnnet-Agoitn
-Algondhm to ypdate am existng
eAishny jBem sn a
’ Vpdate
data souctre.
’Oelete Akyonhn to dolote an eaismg lem
Prom a data shuctre.
Chanactoisdic o! an kgonhn
coled an algorhm. An
Not all procedinoy Com be chanaleristies:
A-tonithm gholdhave the toloromg
shold hawe tha folowmg chansc leridics:
Hn cleonihm shald be clean
’ cleanand thambigecs Alyehm
Each ib step'&ho uld becleon in all
and enamoigoueus
cpects and must oasl to ony says to take
’ well- Dane InputsIf elgonhm
inputs, t shoudd 'be welldefnadinputs
algoithm musd alealy
Quputs;Tha
’ well-Defnedoutpud wil be yeldad omd t shoute
dene tiht well.
bebi well-denad cesalgothm mud be nite,ie
’ Fride neusiTho
shold mo end vp ih am -inginte Jps
be Simple,yensic
’feaihle:The olqyorihm meut ececutel vpon lwill
Cndpracica,cch thad t can be
mot Contah Soma
tho avilooNeonces. Tt mut
Sute tennaloyy on any hing
18)
deigned mud be
lonyoe Tndqpendend:The Algon hvnjud
indepenlod ie d mud be plan intuctiony
Jamg Jomgy cund ye Ahe
in am
Con be inmplemotod epec
Output will be Same,a ted.
Havantagos omd Disacwantays of Ahgonthm
’II ise y to mderdnd od e soltoy
step-wise epreentaion
’ Algo thm is a
toa men problem. problom s brolon dawn do
7n Alyanithm the t eis he
easier or
Smale pieces or sBeps honce,
to Conved into an actel roam.
Prymmon

an algonthm tadee, a
a dong time do
’ hitg
is tima-Conmng
7Bremchng and Losping statemenls
to shaL nAlgonhn.
Oiffenand apploach do deignam algeuhn
1 Top-OoLan tpproch: Atopdoun approach Stats wrdh
idendiyng majon Compononts of syolom, on piagram
hemnto theinloiweevel Componends
dntompongnd Jovel f th module ormpleid,
topmest m
malle
is achiesed. In this we stant
3 incremently acld mole, hd 's coll.
2 Bottom-Up Appnaach ;- Abotom-vp apprach
stants wh dein mos prihnáve
Compononts sproiets do highes dovel bomponent
(19)
SAantng from eny bottom, opertony th povide layen
cf abikocion an mplernontal
How o wite an Algenthm?
Thene ane no shandans
wdlhdofncd eronce en lwnitrg olgeuny
Rathe, t is problom and dapondand. Alaan
Cue meven witento sppot penticulan proglammay
Code. pragramnng longoes shane
As we lenow dhad all (d,foy, Jnile), Flow.
e aos
Dauic Coda Conatuct Thae Common Contruct Can be
Condol it-ele) ete.
wred to wnte on aleyorhm. mamme,bd is
in a shep- by-shep is a poces
bwe lwnste oleyorhns Alqoithm
the care. onidmg
Cnd s etetec She problom doman is wel-dofred.
le sholl
Ihat is Le now the eroblem domauh, for which lwe
a Soltion.
Exampli
Ladlstry to leon olae°hm-tvdnga bg wng an
edample
Problom- Deiem am
amd
Stepl -S1ART
display
declore hee ndecey bc
a,
SBep2-
slep 3-done als o asb
stepa- aclel wouay &
os- stona outpud of step 4 oc
Steps
s\epb prnt
Slep- STop
o0)
Algonhs tell the prociammory haw to Cade he paam
aleyonthm Qan
Can be wtenay
nllonhvly,ho
Sepl SJART AoD

&lep3- Ceatb
SlepA - displayc
Sleps - STop.
SOP
In deign and analy agandms eyhe
Secondmahadis UsedSodobe am olsyahm.
TA modees it eay foy the cunalyt to analy 2e he
al nantoch olenúbions. how the
-sgnomng,
obieve wha opersoy cne beng wed Gnd
plocevs s flowmg
whiting step numdoen is opiono.
we dengm a Golution od aren
proem: A prolem Can be Galveel in mane hon one
Zolutiy

Problom

Soluhion

Hence,meny o soluion olgodhms Can be oleve


tot a ren pnoblam.1he noxd adepis do amoy 2e dhose
prapose Soudion oleyunhny ond'mplomerd h bet
utoble Solution.
Algenhm Camplaaky the Si2eofinpu
is algodhm'X ns
nthe
algovdhm and
Sppose XA6 cm
a

deta ,thetmeand pao the X.


ffieienu
factanyy lwhich deidle
he tuo mam Coenbng the
bocton Timo is mened by tonyn
’ Time ch "as Compn
Mumber hey opendons
the Gontmg alyonhm:
Facton: - Space Js mlaed by
’Space Jegineel byhe
memoypace
he maoimum
dlgonlhm. en) ves the Jning
Compleridy of an oyonithm slyonthi
The reinad
space olot: by e
hme anden he sdona inpet
th Size of
üntems ofnos
Spae Conpleidy oyonthm apraands he
Space Compeity of an the olgonth
siegined by n
Cmound mamorg Spaa
space eywned two
its it cyle. the ollona two Comonn
is equalo no em o the
a spaca neqinelto stoe Contain
Pand thad is ndependoct of the sizeo
data and vaiobles,that ane Contan
Smole Vaiables and
he problem. For example,
Usediprognam, Siz ete. byvaniobley, Whos
pard s a Space segined
vaviadoli
’ A depends on the S2 o the problem.kov esample
Sze Sace
allocotion, Jlecenion Stack
dynamic
er
m
(
ypace Complexity se) ny algordhm P% se) -c+ SP)
Lohene e s he xel parcd and ) s the yonioale pand of
he aloudhm,uich dlepends on inutnce chanacderishe.
tollemgs a imple esample had tie, do erplan
the Concept:
Algonthm: Sum (A,8)
Slepl- sTART
SBep2-Ce-A+B+lo
Step3- Stop BmdCond one conatad
Here we have thuee
vaiae A,
tyees gven
dlata
tonce P)=l+3- Nou, Cpace deponds conwill be mutplieel
Vaniobes and Coneheh types and
accondingy
Time Complesuty the amont
algorihmreplests
of en elgothm toen to
TFime Conpleidy
Nazina by the
o tme con be defned as a
Complaion. Time Jeqinemody meaecl ay
fenco'on Tn), whee n) Cen be
nmeicd step conumes Cortand
providecl each
The mumber e steps
me
addrton ad tuwo intGCy tlees n steps.
n-bit
tor ecample, tme is Ton)- cxn.
Coneqenty he totad Computahon
dor he addiion ad two bis.
Where c s the etalcen dhe
Here, we gd obsenve that To) qaws Jinely
ünput gi22 inneores
Alzon thm Analyis analyzad al tewo
algerhm Can be afta snplamskta
Eficeney f an implomondotion and
dyfeand slgs,before
Thay auFloy: oA Aoympdoic
Anayis onPenomame
’A prioni
Ayis-This ts a theanahcl anoyis o
toctens For eocamyole,
that all ohe
by avmng , cne Contnt and have no
proenan Spead,
On the implementon: lendormane leoement
’A posteien Anayis or olgonidhm. The
amayis f am
This is am empiicl ung programring
Salcded olgenthmis impleneded
exautecl on tangt Comypen
this is then
Jomgua stadis
machne. Inn this anlyis, acdual
ilce
ond saa sagired aue Colectcd
Snnng time
we shall an albout a pisi algonihm analyis .Algendh
en
amyis deals oh he exauhon Jmng tme ef vaniay
opendiona involved. he sunnng tma o am operoton Con
be dened as the numbe o compay irutrucdns executed
par oporudion, dhe
Andyg
nount o aonces Suchas tme and sdeae stanage
nacelhany oeede the olyanihm. Vsuallaythe ficioney
onsmy time of on algouthm s stataf as a
which seltb ho impd Joy dengh to he tme Comypleuty
Aleerhm anyis fromewak inwowes fmdang oudhe
ine talen amd he memory space nagined og a Prgm
to exccute tho procnam. Ti also dotemnes how he irpd
Size o a proram nbenas the Jumningtme the
Plagam.
is lomaon to
In theoehial amadyis o algandhms,itnptotic
eshmate Shoin Copleoidy nthe ay ene e
to eximate the Comploth dndon for onbrhay aginpu
BicO mopdion. mesa na dhon amd Theta motton ane
Used to etmate tha Conplosidy fumcdion fos ane abig

algandhms may vay For inpats a the


The eficioncy a some
algouhns, we had to difenndhatu
Such cane, veane Case amel bet cae
Samo Si22. oY
batween the wont
efiiencie, .
Bet Care rags tmeto eXcate
T an olop talee, Anelet amouncd
thm Calla the bed aeye time
inpd, thentis
of
a Speujc set bat CaLe algondhm
Complssdy The ho oest cae inpd oo sizn. Becaune
lhe aency for olgonithmJ s ns the fastet among
o his input, he
porible.inputs of he Sme Sj ze
ö the
Averua Caue ioalycis
the tne conpleady ONencry ;hem uch athe
Ses of inputs Ceue Ame Coonplexiy
Complesiy is calod ovnae
provide, necotamy ingomoction abut
tvenage Cane analyis on atypical on nondom input.
an algonihm's behaioun aboud the porilble
aumotion
You mut male Some awenage Cae sny
inputs o sizz nto anolyze tho
Wort cane amount of time to
4alce, mascimm called the
an olqonthm inpd,hen ilis
speefe
excite foa spaciic sotof The wowt Cae
Sot
ime Comoley. loe jnp
lwarst Cau for dhe we
alganhm Js shs ameungal dha
o an algohm ' n s }he donge Ynput
o Si2e n. The Simidan i2e balause ay ha
ths
posible cinputs o the
d Si2en.
Madhomdica Notation
wedin voniouy cnens st«dy
widoly
Algonthm diserd prolem wng theSme alyehm.
we com colve folla a standod.The
Thaate,al algohing muwt symbos on Symaoic eoprutiol,
mthomahalnotion ue
which hove a prucise emantie maening
Ampotic Noationy
algoom solutoy,
In onden to choe ime tilen dos n a
abla to jucye he
you mut be acCnately you mut be able
ponhcuan Sotion. Mane A o t i and
to dho timo teton to sen
chace ho bctten ammong tho two.
to chek
To saloct he bad ogorhm it is ecesony
( the oicienay f each blgonthm The feiong exh
(R5) inyatmoion obout
Cat analysis provices necetamy
an algonihm's behevioun on aatypicd on nandom input.
te PoRbde
abot
You mut male Come avnation Cae iny
to anayee tho averane
inputs o size n
me to
ohgorthm Aale, masimum masimum amoundt o
Coalled the
an
Aales inpid,thon itis
d
exeite for a
comeley The wont care
twart Cae timo dhe cwonad cose Snpt
algan/hm s dhe eilncy for amo umy oll' tha
o an n.The olgohm'uny dhe Lomed dha nput
o Sie Yhe Simidan i z2
bocoue
possible cinuts o
Madhomatica Notation
n Voows
Algonthny widelg
dirndt praolems ng the Some algonhm
lwe com solve folla a slandord. The
Theutor, all algoniy mut
methomatial nobtion weesymbolb on Symboic eospraiony,
which hawe a precise Gemantic maming
Aypoic Noadion souto
may have vaaiaus alonthm
Aproblam
chose te bet ogodhm tor a porticalon proless,
In onde to jucyethe tina telcen to un
you mut be ableto
tojudae tho time takonto Sun
choce ho better mony tho two.
To solat he bet algprthm t is meehong to chak
( the opiciency of each blgontom The qfieng eaxh
olgonthm Com be checked by Computme s ime
Conplezity Dhe ctgptodic motadtony halto sepraed the
shothand woy. It Can 9enenly be
Conplaxy
Sapreseilecl af Ahe fostot posible, slowet
postibli
avercye psible o),S (omoya) and (hek
o
(Big
The nototons Guch cy onotadions
CUe Ca Cymptohe cne ued Thee ane the difersnt
n thae
mthenmotical tions that
Cees of Aime Comploity
Biq-ONohtion noion. Big-o the
neprerendadion tor Biq-O bamd o theJning
'ois the expsus the Uppen performance
method wed to cuel to olescube hi
algoutm. IH is
-time an the adgorhm. Big-O spea
en time Conlacity Scenaio conel Can be wied to
Ouscibe h tenfCaas on tho space wel
Ahe exeeution ime eeuired
Ces ibe the
by the olghm the come
names and examples
Teble Rl gve Lome There ndei cue Ynlced
ued to descnbetuncdrons.
Cnds
rom dop to bottom.
Common
Ecamples
Time
O)
Complooty
Conb Addng to the ront dalnked lid
1 onf enty in dSontt aay
m en n cun Unsotedc y
33 O inontei Sanny n itens by'dvide-andCongues
4 0nlan) Quodtic shadoid podh between hwo naey în agph
lubic Smalbnoay Jinacn equtiy
7: Gfe on) Eporenti The Tawe o tenoi pablom.
wwel to expres em
Big-O matadion is geneally
tha fenctions
This natotich
endong prepenty among mainum aymelnd o tme
in Calculatna the problem. Big O
helps do compte
algentm oa
taleen by an
is dojned ees oukpky
outpects and
fon Lc*a(n)
n°mnben e inpuls on
n Canbe any non-nagatve function)
whee too Content
n) cus lwoell as qo) ane
ane tue enly
frene sa
m Such thad
There fenchions
Cond a non-nugtve ieya g), whore
as fon) -O amel
clonuted
an aleo be unctions
The Big-ogo) anetwo mon- nagatve Cotant C.Some
t )and fon)-Ogó)
Shon
epresendtion ef
grophiCad timenrees Conidobly
Tho raingy
ge. Lohene the
Whon n n o e s .
Anogn +2h
Conide fen) 15n4 much
Example ìnchees, n belomes
As the Noee o
n
tence, it domina
n, ndog n and n.
dange ihan and we con Coide he mney
the funcdion to) Theetora, it Cen be
to the ovde o n.
Whitten as 16)= Cn.
fin) andceón) wsl not be Les
The Vales o n foy no ane not
han no: Thoafove, the vaueses han
Coniderd nlevand.
fn)

Big-O Noladion fon) =Cdgn))


undesand the Big-O
w e an Cxamplo dto
naation male eloay
Exampe )=n
Conide tunchin to)=2)+2 c n)
nd sho Contand c such hd fon)
we nacd to
\olnl then

to) =an) +22(2)+2-6


n) n'= 2 4
Hee, t)> g6)

hus, hen nis nesta tham 2,, wee cyet ti)gín).Tn ohen
than
wondst ay n beComescyen, the mng me Annee
Cowid This melardes Cohcudeyhed the eig-0hes
dedemo i luope bolumd! od the algoilhys m-tme:
initetiowy od Big ONottion
Thene ane Certoh imittiory otn the BicO notation o
eapronng the Comnplexidy of leouts.Thee
Jitatio ae a, follows:
’Mamy alyonthms smply too hand to amalee
mathenatey
There moy nay na be Sutfiiecd infomodion to
n he ayery
Calclste the beaviBuy o thé algerhm
toll us how the olanhm grous
’ BigO noyis ony prcblem,
wth the sie of h not hos fiiend
ast oes not 'Conien the progmmng
Tt enanes amartand Contnt Fo exanple, i one
6lonhm tales Cn) me to execete amd the othen
tales o boo00n)tme to eaecte ,hen as per BicC)
boh elgonthmhave equal timebe complozity Tn
Sealime yomhis may aseiows Canhdewton
Umega Votation Omega
the epeentin toy Ormega notaion.
's is lhich am algonithn ponory
descbe he mamne in
lopleity This nototion provices
time
in the bet Care time talen by an alghm
he mnimum amound ee< t is Conideredthat
hus
Go Compde aproadern. band"'o the adgonithm's
Cmega gNe, he AsloLJe
dojned as?
Suntm. Omega
inputs cn oulpds amd
whae, n As amy numbe o functiony. hee
ane two non-negatve
onlyt henes e Contd e
tunchiows ae dre ho uch thod n>no
(30)
Omoga Can aso oe clomoted as fon) S(go) oen
to Oneya o gf. Thu grophical
n is eqlol f)-si(eov)is shon an tig 22.
Sepnaentoion ef S2 (gon)d Ton)s
Seic to be in toy all
The yemcion toàs Content nutiple od ge)
by soms
baundedl balas y.e.il dheoeist Some poitive Contont
Vaes fn. ,Such that
Veugs mon-naçatve ioyen no,
c cind Son
) C x an) for ol nno.
Shows Omoga metation.
Hquo 22
c*gh)

Foemple fo)Qn+s cmd on)n.


Coniden fnctioneontent csuch thet n) (*g).
we meol to nd the
+S=20-+S=s
Lad no thom
g ) = ) =o)=0
Here f ) >g)

n)= n ) 7
Hene )=)
22+5=13
Let n=2,thon

Heo n ) )
to)c*g6).dis Coneucles
hat meya
yed algonhm's m-tme.
(W od ho
(3)
Theta Votion
nepresentation fov "Thela natation.Thota
'e'sthe
vppen boun mel losen bone
noation s uied Lohen the mnrutude.
o an aloenihm ane in the Same onder of
*Theta en be dened as:
Clxn) ta)ca* o)
ingut, on cutpt and i)
lwhene,ns any numbe a Ther functiong
non-hagotve Funchiony
Cond g) ne Aso Contants marmely. c,
true-onlyi thene cne two
cUle
C2 emd a non whene t n
denoed as fo)= Cgo)) Jhen
Thoda Can aluo be n.The qrophi praontotion
As equal to Thake of q f Q.3. The function
=g))s shin in iyue bolnded both obove
cf t ) fn) s
)s Said to be àn o(g)Contant mutples of )
and belw by Some positve exnts Some peitve
mon-hegothve inteyn no,
Contn ca endamd Some
shauy Thata Notostion.
Fige

Mo

eoccmple to undlostnd the Thoda


moation moo cleang
(32
Example Conide tundion to) Ant3 cmd an)= An
for all n3: and fi) -An+3. Onl g) Sn forall n3
Then the LEult of the fencdion will be
ton)= An +3 -A3)+3=1S
0)= 4n =43)=)2
+)=An+3 =A)+3=S
n)= Sn =s)ls Cnel
hone eI s 4 c2sCmd nais 3
e )t)eg
husrhonm the above eution we yetoopicts
Coneludes thod hota noetion Ih Junnn
his dowa bound.
ima
-Hme batween tha vppen bond and

Algoahm Deign Techniguc


ODido and Conquen
( Back ackang method

Diide and Conalen


bai cay tha ee
Conguen approachSus
Divide and problem into pncbloms
osealano the pnsblem bd Smaller is Size
Simidanto the euginal problems ar
sow, once died Cub
SSmoleto combine soutiony o
amod thon
Saved ecwl sivey osolution tO ciginalproblen
Sco erblems to cSeote ane Conquen
secion the dvide
t each Jevel o he
ouppsouch falloshee step:
whole pnoblom s civided
Diide:-n this step
into sevenal Sub probloms.
Conquen:-The Cuo problems CUe
hem ecwvely ondy i hey ane Small enoih
o be Rowed, oYhonise step 1 is erlected.
Conaine:Tn this final step, the Rolution cbtaned G the
Sub prooloms ane Combn to Ceste solution to
he orignal problem.

Subprablem

Comput Conpte
Compte Subproboms Compute
Subproblom (Subproblem Subproblom
we Cam olow he dideamd-Conquon
Chenony
approach ina thuee-sBep proes
Example:
On the
The specije Canpten olonhms ae baed
Dvide covquen apploch:
A: Maimum and minimm bblem
Q Bnny Seanch
3 Sontinea (meee sSot, qyuick sont)
A.Towen o d tanoi.
Fundamedal o Dvide Conqen hstegg
Thau ane too fundamondads o Dvido sConqyen Shetog:
} Rolationa Tovmula
a. stopping Condition
1- Rolationa tomde: T4 ishe onmulathd we gonerte
Hrom dho qNen tochnique. Afer aenensdon oy Fovmla,
we appy D¯c eetayi:e ie break dhe problom nennvely
Solwe tho boken Bopobloms:
Stopena Condition tohon we bneok the problomo n
aShepeng eng
9hatoytham twe naod to leno. thad s
Dide Conguen Conque. So,he Condition
much t e , twe nosd to appy dvido
acunsion sleps o Dsc is called
Lhe he neod to stop on
Soppng Condiion.
and Congusn Appromch:
pplcotims of Ovide anebacon he ConCopt od tha
Follema olegonitm
Conguo Technique: seanch olohmhol-itoal
Seandh The binay abocaled a
m,hich s It wandes by Compaing
Sesnehngan
Seanch Lognithmatie Search. elomod eistng n
mmddle companison,i he
voe both tho
tha tng Aften malng the Genno eonaih
a cortoe aay: ay. hoy had
aets iens dhon the elininatosollowed oy agn
Value eventuoey we ceill
the tateed oil Sech onhe
ho elomon and
sheho
Compne it ith thg

Contnmdle
Contiden Re midUeproces aeps on lapeotng
Nolua. Tho
mo. I we Boand th
can be
hoy
ohe Concledto be
tauqed Value
oue s s Ahe Reach,thent
then t can
empty oter d an thea y
enng not presend
taretis e algandhn,
thod ho Soit shats
pntition- eachane follaed by
enoLJn as
Lwichisao pvot voue hromelemeny cn iayotwo Swb-a
a of he elomsis
y sdacng eoch
whehof he
tho elomot
didingpantidion Js mnade by Compann
Tho Noe companes
volhan the pivaf an
twrththo pvo value onloner losei
holds aa cyreolen vey
them ,od ho CUys
3 Menge Sondi T is a Sondingy oyonhm dhod Gand,dviding
CUncray y malng Compai sons. TH Sknts by
costs
into sub-amay amdthon Wecnnvely thom
Ech o Ahom. A4e he conting s done, iH moigen
back.
Alantages Dride anl Conqen Rucenhaly Solve one
’Dvide and Conquen to as dhe Touer ttanei,
AendSuch
of problems
the bigget
amadhemadicol puzzle.T\ 2s challorgn2Reve no boic
Comoictecl probloms fon wichhe davide
you d Conge appo
am
idaa, bud wth the theý of on dwidng
effont a it worles
it hey lesened thetoothalves and then eolwe"them
man pnoblem into
SoceiLwely. This algondhm is much foiten thon
ethon adorthms cache m
eieny uses momory Gubprublemy
’ IH solwes nple
Space secaue it inetesd ol aceuing the
wthn he cache momory
slawen main nemary
DisalNantap, o Onide cmdConquen
’Since mos otits
Anconporahmg
Seion,
mañenemont.
my
alorish sott
,Jaisnddigh
necesittes

the Spae.
nay ovene
An esplicit tack msy The hecuisn
’It may even Crah hs
qreoten han Ahe
s perfomad ieprouly
Stack pnerend in hecPU.
(36)
Bacletec kng
The Backtrackeg s cm clgorihm-mahed to golwe a
Problom wth an &dditinal iny.Hes a elsave
pproch to explash he probtomy. e cam Say Thd the
is neocod to fned all postible ombnosion
backtralng
o solve an gotimizaon problom

ecis'or endil we t ona hat 'ovkes'!


Sequenes odecisons
In the follawmy iyune one an
Zoch mon-lenoline trecis aa parerd
’Cach
more ohony odes Cit children)
2 Each nodo Jn he te.the hem dho oot, has
eocacty one parent

f as-Reachmg a tree fov


Baclktrackney Can undeslonel
node.
pantieula "goal" La smple- we explere
Undowbtoyquite
Backtrackmg follous i
eoch mod
"explene node Ny "sucay'
To nos, nedun
a goal nae,ctun "failne'!
32
3 bor eoch chld cefy
Eaplane c netn "Succoy'!
B
Auccenfl, 2

4 Rodun "foiene"
detmnos the eaution Joy
Backhackng algonhm Jhe Rotwtion spae or
Sydamaticy SconchangSs Airet Seonck wih any
problem. Baclehackmg a depth- bacdetackn s
baundng tencton. Complec Qetof ondents.
a o imlicid.
be
be eplicit
eplict veotan
Consdunts moy may Jule,wichtrict
lod. which hotict each
Expicit Constrd
Ezpliat dhosenyrom the ojven set
elomont to be dotemine which each
ecd.which Saty
Conthent S octslly
Implicit
n the lodution space,
o the tuples
tho ariteion hnetin
Oynamic praammhg cimiln to lide
üs problon
Dynamic oeminng cowe o
teeniue Bothdecniqes b-proolems that
and-Conquen it don irto, Beweralman diheremce between
bretng meman
Jecwvely. "The he problam
Cam be eswed oupproch pontitiony Sub-pobles
,Pvide Conguen eale tha Gub.
Js Ahat
ind.ependont Sub-prsbems, Solttowy sto
Jnto thein
Sacuvely and dhon Combne dyvmic
wheneassbproblems
problem
Sowe tho oNynaluppicothe whon the
}s Gulb-pnbloms shere
andepnkond thad is when
mot Subpuoblems. Albo, A namic potemnaivy
ut once anol
Sub prdolem
aleyonnms Sowes every Bub table.horeloy aoidh
hon Saves ts cnwerin el
/ seymu
-the twonk ol oComputme the
ri eNser eNeny time the
Sub cbproblem is eneounterol.
Thenejone "Oynamic
Swb problem
progammng-is pplicoble when
ae nol ndepelend, tha is Lwhen Gub
prsblem shane b roblorns 1

Hs Cneody approach, Dyromic prorannm


appied 45 optimi2adion paoelemy end in,he
fon hem he
Can be many pogible soletiows and he Jeainamneas Bis
to And he optmal Salution among hose. But Dynanic
Pranammg apprh s tle difenend eyreedy ogpmch.
choicas n
In eady sautions ane Compited lay
Serial tovwcn wey and in bacletvaclg
his no
f choices is done thons as Dynamic prarammng Compats
its godution botom pby poducing sinem rom Sme
cnd
Sub prablems, and oy rying mam posoilitechoices
cheices boare t aLves atthe ophmal el
The Developmet cy dynamic-pnogramming ogohm
Cam be brokeninto asaquenie ofoun Steps
bus probtoms: Themain probomns ane.dwided inte
Dvids, o
Severl mallen deb prsblems In his he odtioythe Golton
Tho maun proelem s
for dhe Smollen optimd soletoh
h soructue o an coptmat
chanacteuzn tho vole ay n
and JocneWel dano
Solutin. Rub poble
Table,storcue: Tho soedion Jor coch
dhad Can be wed may
s staneo iheteblo,so
mes whoneva ecined.
(34
Conbne, botom-bp Compuction : Tho eolution to man
prblemüs obtaned by combinney h Goltions y Smales
Sub problems i.e Covpule ho vole o an optimod
Solution dna bottom-vp fahion
ootnel southion from Computol ingomaton
Constuct an some
care
CThis sdep is optional aneis negined in
additional injormatorn is neqined fer tmdng at
optmal &olition.) thouyh dyavic
ang bem to be colve follong
Now fov mut tollors the
Pogvammhg apploach st
Conditiony: Batb, that on sowng the
Fmiple Optinality: ! shoile
mate pnobem be nsted shad
shald optmally,soin dhe ma
be Soved opdimall.
tmes eoch Sub proboms Jon çoved
opdmd majaidy
Ccue wJe shouk the man problom,
Podynomicl Bnealeup:-tov Solwmy marn
Bevnaeub problons
probems dvicled into PT am
the porgomamca gmi
and Jor efiient d eub problem to be
the otaJ numba polynomiel mmbe..
mmea:
shold be ad-mat'o o Dynamic
Vaniouy olgoim wnich mac lue
follos
programnng Aechnige
madrix uldipicotin.
Rehain shatet pdth
3 Au paY mam problem
4: Tyawelling Saes
Chanoi:
G choclce Boand
Seguonle
Ao)
8 Asomleyi sehadng.
4 Optmel inany Beandh tree.

You might also like