Вы находитесь на странице: 1из 22

A Gentle Introduction to Algorithm Complexity Analysis

Dionysis "dionyziz" Zindros <dionyziz@gmail.com


<mailto:dionyziz@gmail.com>>
* English <http://discrete.gr/complexity/?en>
* < ttp://dscrete.gr/compexty/?e>
* < ttp://dscrete.gr/compexty/?m>
* spao < ttp://dscrete.gr/compexty/?es>
* Hep trasate <mato:doyzz@gma.com>

Itroducto
A ot of programmers t at mae some of t e cooest ad most usefu
software today, suc as may of t e stuff we see o t e Iteret or use
day, do't ave a t eoretca computer scece bacgroud. T ey're
st pretty awesome ad creatve programmers ad we t a t em for w at
t ey bud.
However, t eoretca computer scece as ts uses ad appcatos ad
ca tur out to be qute practca. I t s artce, targeted at
programmers w o ow t er art but w o do't ave ay t eoretca
computer scece bacgroud, I w preset oe of t e most pragmatc
toos of computer scece: Bg O otato ad agort m compexty
aayss. As someoe w o as wored bot  a computer scece academc
settg ad  budg producto-eve software  t e dustry, t s
s t e too I ave foud to be oe of t e truy usefu oes  practce,
so I ope after readg t s artce you ca appy t  your ow code
to mae t better. After readg t s post, you s oud be abe to
uderstad a t e commo terms computer scetsts use suc as "bg O",
"asymptotc be avor" ad "worst-case aayss".
T s text s aso targeted at t e juor g sc oo ad g sc oo
studets from Greece or ayw ere ese teratoay competg  t e
Iteratoa Oympad  Iformatcs
< ttp://e.wpeda.org/w/Iteratoa_Oympad__Iformatcs>, a
agort ms competto for studets, or ot er smar compettos. As
suc , t does ot ave ay mat ematca prerequstes ad w gve you
t e bacgroud you eed  order to cotue studyg agort ms wt a
frmer uderstadg of t e t eory be d t em. As someoe w o used to
compete  t ese studet compettos, I g y advse you to read
t roug t s w oe troductory matera ad try to fuy uderstad t,
because t w be ecessary as you study agort ms ad ear more
advaced tec ques.
I beeve t s text w be epfu for dustry programmers w o do't
ave too muc experece wt t eoretca computer scece (t s a fact
t at some of t e most sprg software egeers ever wet to
coege). But because t's aso for studets, t may at tmes soud a
tte bt e a textboo. I addto, some of t e topcs  t s text
may seem too obvous to you; for exampe, you may ave see t em durg
your g sc oo years. If you fee you uderstad t em, you ca sp
t em. Ot er sectos go to a bt more dept ad become sg ty
t eoretca, as t e studets competg  t s competto eed to ow
more about t eoretca agort ms t a t e average practtoer. But
t ese t gs are st good to ow ad ot tremedousy ard to foow,
so t's ey we wort your tme. As t e orga text was targeted
at g sc oo studets, o mat ematca bacgroud s requred, so
ayoe wt some programmg experece (.e. f you ow w at recurso
s) w be abe to foow t roug wt out ay probem.
T roug out t s artce, you w fd varous poters t at  you to
terestg matera ofte outsde t e scope of t e topc uder
dscusso. If you're a dustry programmer, t's ey t at you're
famar wt most of t ese cocepts. If you're a juor studet
partcpatg  compettos, foowg t ose s w gve you cues
about ot er areas of computer scece or software egeerg t at you
may ot ave yet expored w c you ca oo at to broade your terests.
Bg O otato ad agort m compexty aayss s somet g a ot of
dustry programmers ad juor studets ae fd ard to uderstad,
fear, or avod atoget er as useess. But t's ot as ard or as
t eoretca as t may seem at frst. Agort m compexty s just a way
to formay measure ow fast a program or agort m rus, so t reay
s qute pragmatc. Let's start by motvatg t e topc a tte bt.
A screes ot of a artfca tegece c aracter  Haf-fe 2
*Fgure 1*: Artfca tegece c aracters  vdeo games use
agort ms to avod obstaces w e avgatg  t e vrtua word

Motvato
We aready ow t ere are toos to measure ow fast a program rus.
T ere are programs caed /profers/ w c measure rug tme 
msecods ad ca ep us optmze our code by spottg botteecs.
W e t s s a usefu too, t s't reay reevat to agort m
compexty. Agort m compexty s somet g desged to compare two
agort ms at t e dea eve gorg ow-eve detas suc as t e
mpemetato programmg aguage, t e ardware t e agort m rus o,
or t e structo set of t e gve CPU. We wat to compare agort ms
 terms of just w at t ey are: Ideas of ow somet g s computed.
Coutg msecods wo't ep us  t at. It's qute possbe t at a
bad agort m wrtte  a ow-eve programmg aguage suc as
assemby < ttp://e.wpeda.org/w/Assemby_aguage> rus muc
qucer t a a good agort m wrtte  a g -eve programmg
aguage suc as Pyt o < ttp://www.pyt o.org/> or Ruby
< ttp://www.ruby-ag.org/e/>. So t's tme to defe w at a "better
agort m" reay s.
As agort ms are programs t at perform just a computato, ad ot
ot er t gs computers ofte do suc as etworg tass or user put
ad output, compexty aayss aows us to measure ow fast a program
s w e t performs computatos. xampes of operatos t at are purey
/computatoa/ cude umerca foatg-pot operatos
< ttp://e.wpeda.org/w/Foatg_pot> suc as addto ad
mutpcato; searc g wt  a database t at fts  RAM for a gve
vaue; determg t e pat a artfca-tegece c aracter w
wa t roug  a vdeo game so t at t ey oy ave to wa a s ort
dstace wt  t er vrtua word (see *Fgure 1*); or rug a
reguar expresso < ttp://www.reguar-expressos.fo/> patter matc
o a strg. Ceary, computato s ubqutous  computer programs.
Compexty aayss s aso a too t at aows us to expa ow a
agort m be aves as t e put grows arger. If we feed t a dfferet
put, ow w t e agort m be ave? If our agort m taes 1 secod to
ru for a put of sze 1000, ow w t be ave f I doube t e put
sze? W t ru just as fast, af as fast, or four tmes sower? I
practca programmg, t s s mportat as t aows us to predct ow
our agort m w be ave w e t e put data becomes arger. For
exampe, f we've made a agort m for a web appcato t at wors
we wt 1000 users ad measure ts rug tme, usg agort m
compexty aayss we ca ave a pretty good dea of w at w appe
oce we get 2000 users stead. For agort mc compettos, compexty
aayss gves us sg t about ow og our code w ru for t e
argest testcases t at are used to test our program's correctess. So f
we've measured our program's be avor for a sma put, we ca get a
good dea of ow t w be ave for arger puts. Let's start by a
smpe exampe: Fdg t e maxmum eemet  a array.

Coutg structos
I t s artce, I' use varous programmg aguages for t e
exampes. However, do't despar f you do't ow a partcuar
programmg aguage. Sce you ow programmg, you s oud be abe to
read t e exampes wt out ay probem eve f you are't famar wt
t e programmg aguage of c oce, as t ey w be smpe ad I wo't
use ay esoterc aguage features. If you're a studet competg 
agort ms compettos, you most ey wor wt C++
< ttp://www.cpuspus.com/doc/tutora/>, so you s oud ave o probem
foowg t roug . I t at case I recommed worg o t e exercses
usg C++ for practce.
T e maxmum eemet  a array ca be ooed up usg a smpe pece of
code suc as t s pece of Javascrpt
< ttp://www.qursmode.org/js/tro. tm> code. Gve a put array A
of sze :
|1.||var| |M = A[ 0 ];|
|2.|
|3.||for| |( ||var| | = 0;  < ; ++ ) {|
|4.|| ||f| |( A[  ] >= M ) {|
|5.|| ||M = A[  ];|
|6.|| ||}|
|7.||}|
Now, t e frst t g we' do s cout ow may /fudameta
structos/ t s pece of code executes. We w oy do t s oce ad
t wo't be ecessary as we deveop our t eory, so bear wt me for a
few momets as we do t s. As we aayze t s pece of code, we wat to
brea t up to smpe structos; t gs t at ca be executed by t e
CPU drecty - or cose to t at. We' assume our processor ca execute
t e foowg operatos as oe structo eac :
* Assgg a vaue to a varabe
* Loog up t e vaue of a partcuar eemet  a array
* Comparg two vaues
* Icremetg a vaue
* Basc art metc operatos suc as addto ad mutpcato
We' assume brac g (t e c oce betwee |f| ad |ese| parts of code
after t e |f| codto as bee evauated) occurs staty ad wo't
cout t ese structos. I t e above code, t e frst e of code s:
|1.||var| |M = A[ 0 ];|
T s requres 2 structos: Oe for oog up A[ 0 ] ad oe for
assgg t e vaue to M (we're assumg t at  s aways at east 1).
T ese two structos are aways requred by t e agort m, regardess
of t e vaue of . T e |for| oop tazato code aso as to aways
ru. T s gves us two more structos; a assgmet ad a comparso:
|1.|| = 0;|
|2.|| < ;|
T ese w ru before t e frst |for| oop terato. After eac |for|
oop terato, we eed two more structos to ru, a cremet of 
ad a comparso to c ec f we' stay  t e oop:
|1.||++;|
|2.|| < ;|
So, f we gore t e oop body, t e umber of structos t s
agort m eeds s 4 + 2. T at s, 4 structos at t e begg of
t e |for| oop ad 2 structos at t e ed of eac terato of w c
we ave . We ca ow defe a mat ematca fucto f(  ) t at, gve
a , gves us t e umber of structos t e agort m eeds. For a
empty |for| body, we ave f(  ) = 4 + 2.

Worst-case aayss
Now, oog at t e |for| body, we ave a array ooup operato ad a
comparso t at appe aways:
|1.||f| |( A[  ] >= M ) { ...|
T at's two structos rg t t ere. But t e |f| body may ru or may
ot ru, depedg o w at t e array vaues actuay are. If t appes
to be so t at |A[  ] >= M|, t e we' ru t ese two addtoa
structos a array ooup ad a assgmet:
|1.||M = A[  ]|
But ow we ca't defe a f(  ) as easy, because our umber of
structos does't deped soey o  but aso o our put. For
exampe, for |A = [ 1, 2, 3, 4 ]| t e agort m w eed more
structos t a for |A = [ 4, 3, 2, 1 ]|. W e aayzg agort ms,
we ofte cosder t e worst-case scearo. W at's t e worst t at ca
appe for our agort m? W e does our agort m eed t e most
structos to compete? I t s case, t s w e we ave a array 
creasg order suc as |A = [ 1, 2, 3, 4 ]|. I t at case, M eeds to
be repaced every sge tme ad so t at yeds t e most structos.
Computer scetsts ave a facy ame for t at ad t ey ca t
/worst-case aayss/; t at's ot g more t a just cosderg t e
case w e we're t e most uucy. So,  t e worst case, we ave 4
structos to ru wt  t e |for| body, so we ave f(  ) = 4 + 2 +
4 = 6 + 4. T s fucto f, gve a probem sze , gves us t e
umber of structos t at woud be eeded  t e worst-case.

Asymptotc be avor
Gve suc a fucto, we ave a pretty good dea of ow fast a
agort m s. However, as I promsed, we wo't be eedg to go t roug
t e tedous tas of coutg structos  our program. Besdes, t e
umber of actua CPU structos eeded for eac programmg aguage
statemet depeds o t e comper of our programmg aguage ad o t e
avaabe CPU structo set (.e. w et er t's a AMD or a Ite
Petum o your PC, or a MIPS processor o your Paystato 2) ad we
sad we'd be gorg t at. We' ow ru our "f" fucto t roug a
"fter" w c w ep us get rd of t ose mor detas t at computer
scetsts prefer to gore.
I our fucto, 6 + 4, we ave two terms: 6 ad 4. I compexty
aayss we oy care about w at appes to t e structo-coutg
fucto as t e program put () grows arge. T s reay goes aog
wt t e prevous deas of "worst-case scearo" be avor: We're
terested  ow our agort m be aves w e treated bady; w e t's
c aeged to do somet g ard. Notce t at t s s reay usefu w e
comparg agort ms. If a agort m beats aot er agort m for a
arge put, t's most probaby true t at t e faster agort m remas
faster w e gve a easer, smaer put. *From t e terms t at we are
cosderg, we' drop a t e terms t at grow sowy ad oy eep t e
oes t at grow fast as  becomes arger.* Ceary 4 remas a 4 as 
grows arger, but 6 grows arger ad arger, so t teds to matter more
ad more for arger probems. T erefore, t e frst t g we w do s
drop t e 4 ad eep t e fucto as f(  ) = 6.
T s maes sese f you t  about t, as t e 4 s smpy a
"tazato costat". Dfferet programmg aguages may requre a
dfferet tme to set up. For exampe, Java eeds some tme to
taze ts vrtua mac e
< ttp://e.wpeda.org/w/Java_vrtua_mac e>. Sce we're
gorg programmg aguage dffereces, t oy maes sese to gore
t s vaue.
T e secod t g we' gore s t e costat mutper  frot of ,
ad so our fucto w become f(  ) = . As you ca see t s
smpfes t gs qute a ot. Aga, t maes some sese to drop t s
mutpcatve costat f we t  about ow dfferet programmg
aguages compe. T e "array ooup" statemet  oe aguage may
compe to dfferet structos  dfferet programmg aguages.
For exampe,  C, dog |A[  ]| does ot cude a c ec t at  s
wt  t e decared array sze, w e  Pasca
< ttp://e.wpeda.org/w/Pasca_%28programmg_aguage%29> t
does. So, t e foowg Pasca code:
|1.||M := A[  ]|
Is t e equvaet of t e foowg  C:
|1.||f| |(  >= 0 &&  <  ) {|
|2.|| ||M = A[  ];|
|3.||}|
So t's reasoabe to expect t at dfferet programmg aguages w
yed dfferet factors w e we cout t er structos. I our exampe
 w c we are usg a dumb comper for Pasca t at s obvous of
possbe optmzatos, Pasca requres 3 structos for eac array
access stead of t e 1 structo C requres. Droppg t s factor
goes aog t e es of gorg t e dffereces betwee partcuar
programmg aguages ad compers ad oy aayzg t e dea of t e
agort m tsef.
T s fter of "droppg a factors" ad of "eepg t e argest
growg term" as descrbed above s w at we ca /asymptotc be avor/.
So t e asymptotc be avor of f(  ) = 2 + 8 s descrbed by t e
fucto f(  ) = . Mat ematcay speag, w at we're sayg ere s
t at we're terested  t e mt of fucto f as  teds to fty;
but f you do't uderstad w at t at p rase formay meas, do't
worry, because t s s a you eed to ow. (O a sde ote,  a
strct mat ematca settg, we woud ot be abe to drop t e costats
 t e mt; but for computer scece purposes, we wat to do t at for
t e reasos descrbed above.) Let's wor a coupe of exampes to
famarze ourseves wt t e cocept.
T e cubc fucto,  bue, overcomes t e ear fucto,  red,
after  = 45
*Fgure 2*: T e ^3 fucto, draw  bue, becomes arger t a t e
1999 fucto, draw  red, after  = 45. After t at pot t remas
arger for ever.
Let us fd t e asymptotc be avor of t e foowg exampe fuctos
by droppg t e costat factors ad by eepg t e terms t at grow t e
fastest.
1.
f(  ) = 5 + 12 gves f(  ) = .
By usg t e exact same reasog as above.
2.
f(  ) = 109 gves f(  ) = 1.
We're droppg t e mutper 109 * 1, but we st ave to put a 1
ere to dcate t at t s fucto as a o-zero vaue.
3.
f(  ) = ^2 + 3 + 112 gves f(  ) = ^2
Here, ^2 grows arger t a 3 for suffcety arge , so we're
eepg t at.

4.
f(  ) = ^3 + 1999 + 1337 gves f(  ) = ^3
ve t oug t e factor  frot of  s qute arge, we ca st
fd a arge eoug  so t at ^3 s bgger t a 1999. As we're
terested  t e be avor for very arge vaues of , we oy eep
^3 (See *Fgure 2*).
5.
f(  ) =  + sqrt(  ) gves f(  ) = 
T s s so because  grows faster t a sqrt(  ) as we crease .
You ca try out t e foowg exampes o your ow:

xercse 1
1. f(  ) = ^6 + 3
2. f(  ) = 2^ + 12
3. f(  ) = 3^ + 2^
4. f(  ) = ^ + 
(Wrte dow your resuts; t e souto s gve beow)
If you're avg troube wt oe of t e above, pug  some arge  ad
see w c term s bgger. Pretty strag tforward, u ?

Compexty
So w at t s s teg us s t at sce we ca drop a t ese
decoratve costats, t's pretty easy to te t e asymptotc be avor
of t e structo-coutg fucto of a program. I fact, ay program
t at does't ave ay oops w ave f(  ) = 1, sce t e umber of
structos t eeds s just a costat (uess t uses recurso; see
beow). Ay program wt a sge oop w c goes from 1 to  w ave
f(  ) = , sce t w do a costat umber of structos before
t e oop, a costat umber of structos after t e oop, ad a
costat umber of structos wt  t e oop w c a ru  tmes.
T s s oud ow be muc easer ad ess tedous t a coutg dvdua
structos, so et's tae a oo at a coupe of exampes to get
famar wt t s. T e foowg PHP < ttp://p p.et/> program c ecs
to see f a partcuar vaue exsts wt  a array A of sze :
|01.||<?p p|
|02.|| ||$exsts| |= fase;|
|03.|| ||for| |( ||$| |= 0; ||$| |< ; ++||$| |) {|
|04.|| ||f| |( ||$A||[ ||$| |] == ||$vaue| |) {|
|05.|| ||$exsts| |= true;|
|06.|| ||brea||;|
|07.|| ||}|
|08.|| ||}|
|09.||?>|
T s met od of searc g for a vaue wt  a array s caed /ear
searc /. T s s a reasoabe ame, as t s program as f(  ) = 
(we' defe exacty w at "ear" meas  t e ext secto). You may
otce t at t ere's a "brea" statemet ere t at may mae t e program
termate sooer, eve after a sge terato. But reca t at we're
terested  t e worst-case scearo, w c for t s program s for t e
array A to ot cota t e vaue. So we st ave f(  ) = .

xercse 2

Systematcay aayze t e umber of structos t e above PHP program


eeds wt respect to   t e worst-case to fd f(  ), smary to
ow we aayzed our frst Javascrpt program. T e verfy t at,
asymptotcay, we ave f(  ) = .
Let's oo at a Pyt o program w c adds two array eemets toget er to
produce a sum w c t stores  aot er varabe:
|1.||v ||=| |a[ ||0| |] ||+| |a[ ||1| |]|
Here we ave a costat umber of structos, so we ave f(  ) = 1.
T e foowg program  C++ c ecs to see f a vector (a facy array)
amed A of sze  cotas t e same two vaues ayw ere wt  t:
|01.||boo| |dupcate = ||fase||;|
|02.||for| |( ||t| | = 0;  < ; ++ ) {|
|03.|| ||for| |( ||t| |j = 0; j < ; ++j ) {|
|04.|| ||f| |(  != j && A[  ] == A[ j ] ) {|
|05.|| ||dupcate = ||true||;|
|06.|| ||brea||;|
|07.|| ||}|
|08.|| ||}|
|09.|| ||f| |( dupcate ) {|
|10.|| ||brea||;|
|11.|| ||}|
|12.||}|
As ere we ave two ested oops wt  eac ot er, we' ave a
asymptotc be avor descrbed by f(  ) = ^2 .
*Rue of t umb*: Smpe programs ca be aayzed by coutg t e ested
oops of t e program. A sge oop over  tems yeds f(  ) = . A
oop wt  a oop yeds f(  ) = ^2 . A oop wt  a oop wt  a
oop yeds f(  ) = ^3 .
If we ave a program t at cas a fucto wt  a oop ad we ow t e
umber of structos t e caed fucto performs, t's easy to
determe t e umber of structos of t e w oe program. Ideed, et's
tae a oo at t s C exampe:
|1.||t| |;|
|2.||for| |(  = 0;  < ; ++ ) {|
|3.|| ||f(  );|
|4.||}|
If we ow t at |f(  )| s a fucto t at performs exacty 
structos, we ca t e ow t at t e umber of structos of t e
w oe program s asymptotcay ^2 , as t e fucto s caed exacty
 tmes.
*Rue of t umb*: Gve a seres of for oops t at are sequeta, t e
sowest of t em determes t e asymptotc be avor of t e program. Two
ested oops foowed by a sge oop s asymptotcay t e same as t e
ested oops aoe, because t e ested oops /domate/ t e smpe oop.
Now, et's swtc over to t e facy otato t at computer scetsts
use. W e we've fgured out t e exact suc f asymptotcay, we' say
t at our program s ( f(  ) ). For exampe, t e above programs are (
1 ), ( ^2 ) ad ( ^2 ) respectvey. (  ) s proouced "t eta of
". Sometmes we say t at f(  ), t e orga fucto coutg t e
structos cudg t e costats, s ( somet g ). For exampe, we
may say t at f(  ) = 2 s a fucto t at s (  ) ot g ew
ere. We ca aso wrte 2 (  ), w c s proouced as "two  s
t eta of ". Do't get cofused about t s otato: A t's sayg s
t at f we've couted t e umber of structos a program eeds ad
t ose are 2, t e t e asymptotc be avor of our agort m s descrbed
by , w c we foud by droppg t e costats. Gve t s otato, t e
foowg are some true mat ematca statemets:
1. ^6 + 3 ( ^6 )
2. 2^ + 12 ( 2^ )
3. 3^ + 2^ ( 3^ )
4. ^ +  ( ^ )
By t e way, f you soved xercse 1 from above, t ese are exacty t e
aswers you s oud ave foud.
*We ca t s fucto, .e. w at we put wt  ( ere ), t e /tme
compexty/ or just /compexty/ of our agort m.* So a agort m wt
(  ) s of compexty . We aso ave speca ames for ( 1 ), ( 
), ( ^2 ) ad ( og(  ) ) because t ey occur very ofte. We say t at
a ( 1 ) agort m s a /costat-tme agort m/, (  ) s /ear/,
( ^2 ) s /quadratc/ ad ( og(  ) ) s /ogart mc/ (do't worry
f you do't ow w at ogart ms are yet we' get to t at  a mute).
*Rue of t umb*: Programs wt a bgger ru sower t a programs wt
a smaer .
A exampe of surfaces dde  a vdeo game
*Fgure 3*: A payer t at s ocated  t e yeow dot w ot see t e
s adowed areas. Spttg t e word  sma fragmets ad sortg t em
by t er dstace to t e payer s oe way to sove t e vsbty probem.

Bg-O otato
Now, t's sometmes true t at t w be ard to fgure out exacty t e
be avor of a agort m  t s fas o as we dd above, especay for
more compex exampes. However, we w be abe to say t at t e be avor
of our agort m w ever exceed a certa boud. T s w mae fe
easer for us, as we wo't ave to specfy exacty ow fast our
agort m rus, eve w e gorg costats t e way we dd before. A
we' ave to do s fd a certa boud. T s s expaed easy wt
a exampe.
A famous probem computer scetsts use for teac g agort ms s t e
/sortg probem/. I t e sortg probem, a array A of sze  s gve
(souds famar?) ad we are ased to wrte a program t at sorts t s
array. T s probem s terestg because t s a pragmatc probem 
rea systems. For exampe, a fe exporer eeds to sort t e fes t
dspays by ame so t at t e user ca avgate t em wt ease. Or, as
aot er exampe, a vdeo game may eed to sort t e 3D objects dspayed
 t e word based o t er dstace from t e payer's eye sde t e
vrtua word  order to determe w at s vsbe ad w at s't,
somet g caed t e Vsbty Probem
< ttp://e.wpeda.org/w/Hdde_surface_determato> (see *Fgure
3*). T e objects t at tur out to be cosest to t e payer are t ose
vsbe, w e t ose t at are furt er may get dde by t e objects 
frot of t em. Sortg s aso terestg because t ere are may
agort ms to sove t, some of w c are worse t a ot ers. It's aso
a easy probem to defe ad to expa. So et's wrte a pece of code
t at sorts a array.
Here s a effcet way to mpemet sortg a array  Ruby. (Of
course, Ruby supports sortg arrays usg bud- fuctos w c you
s oud use stead, ad w c are certay faster t a w at we' see
ere. But t s s ere for ustrato purposes.)
|01.||b = []|
|02.||.tmes ||do|
|03.|| ||m = a[ ||0| |]|
|04.|| ||m = ||0|
|05.|| ||a.eac _wt _dex ||do| ||eemet, ||
|06.|| ||f| |eemet < m|
|07.|| ||m = eemet|
|08.|| ||m = |
|09.|| ||ed|
|10.|| ||ed|
|11.|| ||a.deete_at( m )|
|12.|| ||b << m|
|13.||ed|
T s met od s caed seecto sort
< ttp://e.wpeda.org/w/Seecto_sort>. It fds t e mmum of
our array (t e array s deoted a above, w e t e mmum vaue s
deoted m ad m s ts dex), puts t at t e ed of a ew array (
our case b), ad removes t from t e orga array. T e t fds t e
mmum betwee t e remag vaues of our orga array, appeds t at
to our ew array so t at t ow cotas two eemets, ad removes t
from our orga array. It cotues t s process ut a tems ave
bee removed from t e orga ad ave bee serted to t e ew
array, w c meas t at t e array as bee sorted. I t s exampe, we
ca see t at we ave two ested oops. T e outer oop rus  tmes, ad
t e er oop rus oce for eac eemet of t e array a. W e t e
array a tay as  tems, we remove oe array tem  eac
terato. So t e er oop repeats  tmes durg t e frst terato
of t e outer oop, t e | - 1| tmes, t e | - 2| tmes ad so fort ,
ut t e ast terato of t e outer oop durg w c t oy rus oce.
It's a tte arder to evauate t e compexty of t s program, as we'd
ave to fgure out t e sum 1 + 2 + ... + ( - 1) + . But we ca for
sure fd a "upper boud" for t. T at s, we ca ater our program
(you ca do t at  your md, ot  t e actua code) to mae t
*worse* t a t s ad t e fd t e compexty of t at ew program t at
we derved. If we ca fd t e compexty of t e worse program t at
we've costructed, t e we ow t at our orga program s at most
t at bad, or maybe better. T at way, f we fd out a pretty good
compexty for our atered program, w c s worse t a our orga, we
ca ow t at our orga program w ave a pretty good compexty
too et er as good as our atered program or eve better.
Let's ow t  of t e way to edt t s exampe program to mae t
easer to fgure out ts compexty. But et's eep  md t at we ca
oy mae t worse, .e. mae t tae up more structos, so t at our
estmate s meagfu for our orga program. Ceary we ca ater
t e er oop of t e program to aways repeat exacty  tmes stead
of a varyg umber of tmes. Some of t ese repettos w be useess,
but t w ep us aayze t e compexty of t e resutg agort m.
If we mae t s smpe c age, t e t e ew agort m t at we've
costructed s ceary ( ^2 ), because we ave two ested oops w ere
eac repeats exacty  tmes. If t at s so, we say t at t e orga
agort m s O( ^2 ). O( ^2 ) s proouced "bg o of  squared".
W at t s says s t at our program s asymptotcay o worse t a ^2 .
It may eve be better t a t at, or t may be t e same as t at. By t e
way, f our program s deed ( ^2 ), we ca st say t at t's O(
^2 ). To ep you reaze t at, mage aterg t e orga program
 a way t at does't c age t muc , but st maes t a tte worse,
suc as addg a meagess structo at t e begg of t e
program. Dog t s w ater t e structo-coutg fucto by a
smpe costat, w c s gored w e t comes to asymptotc be avor.
So a program t at s ( ^2 ) s aso O( ^2 ).
But a program t at s O( ^2 ) may ot be ( ^2 ). For exampe, ay
program t at s (  ) s aso O( ^2 )  addto to beg O(  ). If
we mage t e t at a (  ) program s a smpe |for| oop t at repeats
 tmes, we ca mae t worse by wrappg t  aot er |for| oop w c
repeats  tmes as we, t us producg a program wt f(  ) = ^2 . To
geeraze t s, ay program t at s ( a ) s O( b ) w e b s worse
t a a. Notce t at our aterato to t e program does't eed to gve
us a program t at s actuay meagfu or equvaet to our orga
program. It oy eeds to perform more structos t a t e orga
for a gve . A we're usg t for s coutg structos, ot
actuay sovg our probem.
So, sayg t at our program s O( ^2 ) s beg o t e safe sde: We've
aayzed our agort m, ad we've foud t at t's ever worse t a ^2 .
But t coud be t at t's  fact ^2 . T s gves us a good estmate of
ow fast our program rus. Let's go t roug a few exampes to ep you
famarze yoursef wt t s ew otato.

xercse 3
Fd out w c of t e foowg are true:
1. A (  ) agort m s O(  )
2. A (  ) agort m s O( ^2 )
3. A ( ^2 ) agort m s O( ^3 )
4. A (  ) agort m s O( 1 )
5. A O( 1 ) agort m s ( 1 )
6. A O(  ) agort m s ( 1 )

Souto
1. We ow t at t s s true as our orga program was (  ). We ca
ac eve O(  ) wt out aterg our program at a.
2. As ^2 s worse t a , t s s true.
3. As ^3 s worse t a ^2 , t s s true.
4. As 1 s ot worse t a , t s s fase. If a program taes 
structos asymptotcay (a ear umber of structos), we
ca't mae t worse ad ave t tae oy 1 structo
asymptotcay (a costat umber of structos).
5. T s s true as t e two compextes are t e same.
6. T s may or may ot be true depedg o t e agort m. I t e
geera case t's fase. If a agort m s ( 1 ), t e t
certay s O(  ). But f t's O(  ) t e t may ot be ( 1 ).
For exampe, a (  ) agort m s O(  ) but ot ( 1 ).

xercse 4

Use a art metc progresso sum to prove t at t e above program s ot


oy O( ^2 ) but aso ( ^2 ). If you do't ow w at a art metc
progresso s, oo t up o Wpeda
< ttp://e.wpeda.org/w/1_%2B_2_%2B_3_%2B_4_%2B_%2%80%A6> t's
easy.
Because t e O-compexty of a agort m gves a /upper boud/ for t e
actua compexty of a agort m, w e gves t e actua compexty
of a agort m, we sometmes say t at t e gves us a /tg t boud/.
If we ow t at we've foud a compexty boud t at s ot tg t, we ca
aso use a ower-case o to deote t at. For exampe, f a agort m s
(  ), t e ts tg t compexty s . T e t s agort m s bot O( 
) ad O( ^2 ). As t e agort m s (  ), t e O(  ) boud s a tg t
oe. But t e O( ^2 ) boud s ot tg t, ad so we ca wrte t at t e
agort m s o( ^2 ), w c s proouced "sma o of  squared" to
ustrate t at we ow our boud s ot tg t. It's better f we ca
fd tg t bouds for our agort ms, as t ese gve us more formato
about ow our agort m be aves, but t's ot aways easy to do.

xercse 5
Determe w c of t e foowg bouds are tg t bouds ad w c are
ot tg t bouds. C ec to see f ay bouds may be wrog. Use o(
otato ) to ustrate t e bouds t at are ot tg t.
1. A (  ) agort m for w c we foud a O(  ) upper boud.
2. A ( ^2 ) agort m for w c we foud a O( ^3 ) upper boud.
3. A ( 1 ) agort m for w c we foud a O(  ) upper boud.
4. A (  ) agort m for w c we foud a O( 1 ) upper boud.
5. A (  ) agort m for w c we foud a O( 2 ) upper boud.

Souto
1. I t s case, t e compexty ad t e O compexty are t e same, so
t e boud s tg t.
2. Here we see t at t e O compexty s of a arger scae t a t e
compexty so t s boud s ot tg t. Ideed, a boud of O( ^2 )
woud be a tg t oe. So we ca wrte t at t e agort m s o( ^3 ).
3. Aga we see t at t e O compexty s of a arger scae t a t e
compexty so we ave a boud t at s't tg t. A boud of O( 1 )
woud be a tg t oe. So we ca pot out t at t e O(  ) boud s
ot tg t by wrtg t as o(  ).
4. We must ave made a mstae  cacuatg t s boud, as t's
wrog. It's mpossbe for a (  ) agort m to ave a upper boud
of O( 1 ), as  s a arger compexty t a 1. Remember t at O gves
a upper boud.
5. T s may seem e a boud t at s ot tg t, but t s s ot
actuay true. T s boud s  fact tg t. Reca t at t e
asymptotc be avor of 2 ad  are t e same, ad t at O ad are
oy cocered wt asymptotc be avor. So we ave t at O( 2 ) =
O(  ) ad t erefore t s boud s tg t as t e compexty s t e
same as t e .
*Rue of t umb*: It's easer to fgure out t e O-compexty of a
agort m t a ts -compexty.
You may be gettg a tte overw emed wt a t s ew otato by
ow, but et's troduce just two more symbos before we move o to a
few exampes. T ese are easy ow t at you ow , O ad o, ad we wo't
use t em muc ater  t s artce, but t's good to ow t em ow t at
we're at t. I t e exampe above, we modfed our program to mae t
worse (.e. tag more structos ad t erefore more tme) ad
created t e O otato. O s meagfu because t tes us t at our
program w ever be sower t a a specfc boud, ad so t provdes
vauabe formato so t at we ca argue t at our program s good
eoug . If we do t e opposte ad modfy our program to mae t *better*
ad fd out t e compexty of t e resutg program, we use t e
otato . t erefore gves us a compexty t at we ow our program
wo't be better t a. T s s usefu f we wat to prove t at a program
rus sowy or a agort m s a bad oe. T s ca be usefu to argue
t at a agort m s too sow to use  a partcuar case. For exampe,
sayg t at a agort m s ( ^3 ) meas t at t e agort m s't
better t a ^3 . It mg t be ( ^3 ), as bad as ( ^4 ) or eve
worse, but we ow t's at east somew at bad. So gves us a /ower
boud/ for t e compexty of our agort m. Smary to , we can write
if e kno that our bound isn't tight. For example, a ( n^3 )
algorithm is ( n^4 ) and ( n^2 ). (  ) s proouced "bg omega of
", w e ( n ) is pronounced "small omega of n".

Exercise 6
For the folloing complexities rite don a tight and a non-tight O
bound, and a tight and non-tight boud of your c oce, provdg t ey
exst.
1. ( 1 )
2. ( sqrt(  ) )
3. (  )
4. ( ^2 )
5. ( ^3 )

Souto
T s s a strag t-forward appcato of t e deftos above.
1. T e tg t bouds w be O( 1 ) ad ( 1 ). A o-tg t O-boud
woud be O(  ). Reca t at O gves us a upper boud. As  s of
arger scae t a 1 t s s a o-tg t boud ad we ca wrte t as
o(  ) as we. But we caot fd a o-tg t boud for , as we
ca't get ower t a 1 for t ese fuctos. So we' ave to do wt
t e tg t boud.
2. T e tg t bouds w ave to be t e same as t e compexty, so
t ey are O( sqrt(  ) ) ad ( sqrt(  ) ) respectvey. For
o-tg t bouds we ca ave O(  ), as  s arger t a sqrt(  )
ad so t s a upper boud for sqrt(  ). As we ow t s s a
o-tg t upper boud, we ca aso wrte t as o(  ). For a ower
boud t at s ot tg t, we ca smpy use ( 1 ). As we ow t at
t s boud s ot tg t, we ca aso wrte t as ( 1 ).
3. The tight bounds are O( n ) and (  ). Two o-tg t bouds coud
be ( 1 ) and o( n^3 ). These are in fact pretty bad bounds, as they
are far from the original complexities, but they are still valid
using our definitions.
4. The tight bounds are O( n^2 ) and ( ^2 ). For o-tg t bouds we
coud aga use ( 1 ) and o( n^3 ) as in our previous example.
5. The tight bounds are O( n^3 ) and ( ^3 ) respectvey. Two
o-tg t bouds coud be ( sqrt( n ) n^2 ) and o( sqrt( n ) n^3 ).
Although these bounds are not tight, they're better than the ones e
gave above.
The reason e use O and stead of eve t oug O ad ca aso gve
tg t bouds s t at we may ot be abe to te f a boud we've foud
s tg t, or we may just ot wat to go t roug t e process of
scrutzg t so muc .
If you do't fuy remember a t e dfferet symbos ad t er uses,
do't worry about t too muc rg t ow. You ca aways come bac ad
oo t em up. T e most mportat symbos are O ad .
Aso ote t at at oug gves us a ower-boud be avor for our
fucto (.e. we've mproved our program ad made t perform ess
structos) we're st referrg to a "worst-case" aayss. T s s
because we're feedg our program t e worst possbe put for a gve 
ad aayzg ts be avor uder t s assumpto.
T e foowg tabe dcates t e symbos we just troduced ad t er
correspodece wt t e usua mat ematca symbos of comparsos t at
we use for umbers. T e reaso we do't use t e usua symbos ere ad
use Gree etters stead s to pot out t at we're dog a asymptotc
be avor comparso, ot just a smpe comparso.
Asymptotc comparso operator Numerc comparso operator
Our agort m s *o*( somet g ) A umber s *<* somet g
Our agort m s *O*( somet g ) A umber s ** somet g
Our agort m s **( somet g ) A umber s *=* somet g
Our agort m s **( somet g ) A umber s ** somet g
Our agort m s **( something ) A number is *>* something
*Rule of thumb*: While all the symbols O, o, , and are useful at
times, O is the one used more commonly, as it's easier to determine than
and more practically useful than .
T e og fucto s muc ower t a t e square root fucto, w c , 
tur, s muc ower t a t e ear fucto eve for sma 
*Fgure 4*: A comparso of t e fuctos , sqrt(  ), ad og(  ).
Fucto , t e ear fucto, draw  gree at t e top, grows muc
faster t a t e square root fucto, draw  red  t e mdde, w c ,
 tur, grows muc faster t a t e og(  ) fucto draw  bue at
t e bottom of t s pot. ve for sma  suc as  = 100, t e
dfferece s qute proouced.

Logart ms
If you ow w at ogart ms are, fee free to sp t s secto. As a
ot of peope are ufamar wt ogart ms, or just ave't used t em
muc recety ad do't remember t em, t s secto s ere as a
troducto for t em. T s text s aso for youger studets t at
ave't see ogart ms at sc oo yet. Logart ms are mportat because
t ey occur a ot w e aayzg compexty. A /ogart m/ s a
operato apped to a umber t at maes t qute smaer muc e a
square root of a umber. So f t ere's oe t g you wat to remember
about ogart ms s t at t ey tae a umber ad mae t muc smaer
t a t e orga (See *Fgure 4*). Now,  t e same way t at square
roots are t e verse operato of squarg somet g, ogart ms are
t e verse operato of expoetatg somet g. T s s't as ard as
t souds. It's better expaed wt a exampe. Cosder t e equato:
2^x = 1024
We ow ws to sove t s equato for x. So we as ourseves: W at s
t e umber to w c we must rase t e base 2 so t at we get 1024? T at
umber s 10. Ideed, we ave 2^10 = 1024, w c s easy to verfy.
Logart ms ep us deote t s probem usg ew otato. I t s case,
10 s t e ogart m of 1024 ad we wrte t s as og( 1024 ) ad we read
t as "t e ogart m of 1024". Because we're usg 2 as a base, t ese
ogart ms are caed base 2 ogart ms. T ere are ogart ms  ot er
bases, but we' oy use base 2 ogart ms  t s artce. If you're a
studet competg  teratoa compettos ad you do't ow about
ogart ms, I g y recommed t at you practce your ogart ms
< ttp://tutora.mat .amar.edu/Casses/Ag/LogFuctos.aspx> after
competg t s artce. I computer scece, base 2 ogart ms are muc
more commo t a ay ot er types of ogart ms. T s s because we ofte
oy ave two dfferet ettes: 0 ad 1. We aso ted to cut dow oe
bg probem to aves, of w c t ere are aways two. So you oy eed
to ow about base-2 ogart ms to cotue wt t s artce.

xercse 7
Sove t e equatos beow. Deote w at ogart m you're fdg  eac
case. Use oy ogart ms base 2.
1. 2^x = 64
2. (2^2 )^x = 64
3. 4^x = 4
4. 2^x = 1
5. 2^x + 2^x = 32
6. (2^x ) * (2^x ) = 64

Souto
T ere s ot g more to t s t a appyg t e deas defed above.
1. By tra ad error we ca fd t at x = 6 ad so og( 64 ) = 6.
2. Here we otce t at (2^2 )^x , by t e propertes of expoets, ca
be wrtte as 2^2x . So we ave t at 2x = 6 because og( 64 ) = 6
from t e prevous resut ad t erefore x = 3.
3. Usg our owedge from t e prevous equato, we ca wrte 4 as
2^2 ad so our equato becomes (2^2 )^x = 4 w c s t e same as
2^2x = 4. T e we otce t at og( 4 ) = 2 because 2^2 = 4 ad
t erefore we ave t at 2x = 2. So x = 1. T s s ready observed
from t e orga equato, as usg a expoet of 1 yeds t e
base as a resut.
4. Reca t at a expoet of 0 yeds a resut of 1. So we ave og( 1
) = 0 as 2^0 = 1, ad so x = 0.
5. Here we ave a sum ad so we ca't tae t e ogart m drecty.
However we otce t at 2^x + 2^x s t e same as 2 * (2^x ). So we've
mutped  yet aot er two, ad t erefore t s s t e same as 2^x
+ 1 ad ow a we ave to do s sove t e equato 2^x + 1 = 32. We
fd t at og( 32 ) = 5 ad so x + 1 = 5 ad t erefore x = 4.
6. We're mutpyg toget er two powers of 2, ad so we ca jo t em
by otcg t at (2^x ) * (2^x ) s t e same as 2^2x . T e a we
eed to do s to sove t e equato 2^2x = 64 w c we aready
soved above ad so x = 3.
*Rue of t umb*: For competto agort ms mpemeted  C++, oce
you've aayzed your compexty, you ca get a roug estmate of ow
fast your program w ru by expectg t to perform about 1,000,000
operatos per secod, w ere t e operatos you cout are gve by t e
asymptotc be avor fucto descrbg your agort m. For exampe, a
(  ) agort m taes about a secod to process t e put for  =
1,000,000.
factora( 5 ) -> factora( 4 ) -> factora( 3 ) -> factora( 2 ) ->
factora( 1 )
*Fgure 5*: T e recurso performed by t e factora fucto.

Recursve compexty
Let's ow tae a oo at a recursve fucto. A /recursve fucto/ s
a fucto t at cas tsef. Ca we aayze ts compexty? T e
foowg fucto, wrtte  Pyt o, evauates t e factora
< ttp://e.wpeda.org/w/Factora> of a gve umber. T e
factora of a postve teger umber s foud by mutpyg t wt
a t e prevous postve tegers toget er. For exampe, t e factora
of 5 s 5 * 4 * 3 * 2 * 1. We deote t at "5!" ad proouce t "fve
factora" (some peope prefer to proouce t by screamg t out aoud
e "FIV!!!")
|1.||def| |factora(  ):|
|2.|| ||f| | ||=||=| |1||:|
|3.|| ||retur| |1|
|4.|| ||retur| | ||*| |factora(  ||-| |1| |)|
Let us aayze t e compexty of t s fucto. T s fucto does't
ave ay oops  t, but ts compexty s't costat et er. W at we
eed to do to fd out ts compexty s aga to go about coutg
structos. Ceary, f we pass some  to t s fucto, t w
execute tsef  tmes. If you're usure about t at, ru t "by ad"
ow for  = 5 to vadate t at t actuay wors. For exampe, for  =
5, t w execute 5 tmes, as t w eep decreasg  by 1  eac
ca. We ca see t erefore t at t s fucto s t e (  ).
If you're usure about t s fact, remember t at you ca aways fd t e
exact compexty by coutg structos. If you ws , you ca ow try
to cout t e actua structos performed by t s fucto to fd a
fucto f(  ) ad see t at t's deed ear (reca t at ear
meas (  )).
See *Fgure 5* for a dagram to ep you uderstad t e recursos
performed w e factora( 5 ) s caed.
T s s oud cear up w y t s fucto s of ear compexty.
Bary searc g  a array
*Fgure 6*: T e recurso performed by bary searc . T e A argumet for
eac ca s g g ted  bac. T e recurso cotues ut t e
array examed cossts of oy oe eemet. Courtesy of Lue Frac.

Logart mc compexty


Oe famous probem  computer scece s t at of searc g for a vaue
wt  a array. We soved t s probem earer for t e geera case.
T s probem becomes terestg f we ave a array w c s sorted ad
we wat to fd a gve vaue wt  t. Oe met od to do t at s caed
/bary searc /. We oo at t e mdde eemet of our array: If we fd
t t ere, we're doe. Ot erwse, f t e vaue we fd t ere s bgger
t a t e vaue we're oog for, we ow t at our eemet w be o
t e eft part of t e array. Ot erwse, we ow t' be o t e rg t
part of t e array. We ca eep cuttg t ese smaer arrays  aves
ut we ave a sge eemet to oo at. Here's t e met od usg
pseudocode:
|01.||def| |barySearc ( A, , vaue ):|
|02.|| ||f| | ||=| |1||:|
|03.|| ||f| |A[ ||0| |] ||=| |vaue:|
|04.|| ||retur| |true|
|05.|| ||ese||:|
|06.|| ||retur| |fase|
|07.|| ||f| |vaue < A[  ||/| |2| |]:|
|08.|| ||retur| |barySearc ( A[ ||0.||..(  ||/| |2| |-| |1|
|) ],  ||/| |2| |-| |1||, vaue )|
|09.|| ||ese| |f| |vaue > A[  ||/| |2| |]:|
|10.|| ||retur| |barySearc ( A[ (  ||/| |2| |+| |1| |)... ],
 ||/| |2| |-| |1||, vaue )|
|11.|| ||ese||:|
|12.|| ||retur| |true|
T s pseudocode s a smpfcato of t e actua mpemetato. I
practce, t s met od s easer descrbed t a mpemeted, as t e
programmer eeds to tae care of some mpemetato ssues. T ere are
off-by-oe errors ad t e dvso by 2 may ot aways produce a
teger vaue ad so t's ecessary to foor() or ce() t e vaue. But
we ca assume for our purposes t at t w aways succeed, ad we'
assume our actua mpemetato  fact taes care of t e off-by-oe
errors, as we oy wat to aayze t e compexty of t s met od. If
you've ever mpemeted bary searc before, you may wat to do t s
 your favourte programmg aguage. It's a truy eg teg edeavor.
See *Fgure 6* to ep you uderstad t e way bary searc operates.
If you're usure t at t s met od actuay wors, tae a momet ow to
ru t by ad  a smpe exampe ad covce yoursef t at t
actuay wors.
Let us ow attempt to aayze t s agort m. Aga, we ave a recursve
agort m  t s case. Let's assume, for smpcty, t at t e array s
aways cut  exacty a af, gorg just ow t e + 1 ad - 1 part 
t e recursve ca. By ow you s oud be covced t at a tte c age
suc as gorg + 1 ad - 1 wo't affect our compexty resuts. T s
s a fact t at we woud ormay ave to prove f we wated to be
prudet from a mat ematca pot of vew, but practcay t s
tutvey obvous. Let's assume t at our array as a sze t at s a
exact power of 2, for smpcty. Aga t s assumpto does't c age
t e fa resuts of our compexty t at we w arrve at. T e
worst-case scearo for t s probem woud appe w e t e vaue we're
oog for does ot occur  our array at a. I t at case, we'd start
wt a array of sze   t e frst ca of t e recurso, t e get a
array of sze  / 2  t e ext ca. T e we' get a array of sze 
/ 4  t e ext recursve ca, foowed by a array of sze  / 8 ad
so fort . I geera, our array s spt  af  every ca, ut we
reac 1. So, et's wrte t e umber of eemets  our array for every ca:
1. 0^t terato: 
2. 1^st terato:  / 2
3. 2^d terato:  / 4
4. 3^rd terato:  / 8
5. ...
6. ^t terato:  / 2^
7. ...
8. ast terato: 1
Notce t at  t e -t terato, our array as  / 2^ eemets. T s
s because  every terato we're cuttg our array to af, meag
we're dvdg ts umber of eemets by two. T s trasates to
mutpyg t e deomator wt a 2. If we do t at  tmes, we get  /
2^ . Now, t s procedure cotues ad wt every arger  we get a
smaer umber of eemets ut we reac t e ast terato  w c we
ave oy 1 eemet eft. If we ws to fd  to see  w at terato
t s w tae pace, we ave to sove t e foowg equato:
1 =  / 2^
T s w oy be true w e we ave reac ed t e fa ca to t e
barySearc () fucto, ot  t e geera case. So sovg for  ere
w ep us fd  w c terato t e recurso w fs .
Mutpyg bot sdes by 2^ we get:
2^ = 
Now, t s equato s oud oo famar f you read t e ogart ms
secto above. Sovg for  we ave:

 = og(  )
T s tes us t at t e umber of teratos requred to perform a bary
searc s og(  ) w ere  s t e umber of eemets  t e orga array.
If you t  about t, t s maes some sese. For exampe, tae  = 32,
a array of 32 eemets. How may tmes do we ave to cut t s  af
to get oy 1 eemet? We get: 32 16 8 4 2 1. We dd t s 5
tmes, w c s t e ogart m of 32. T erefore, t e compexty of bary
searc s ( og(  ) ).
T s ast resut aows us to compare bary searc wt ear searc ,
our prevous met od. Ceary, as og(  ) s muc smaer t a , t s
reasoabe to cocude t at bary searc s a muc faster met od to
searc wt  a array t e ear searc , so t may be advsabe to
eep our arrays sorted f we wat to do may searc es wt  t em.
*Rue of t umb*: Improvg t e asymptotc rug tme of a program
ofte tremedousy creases ts performace, muc more t a ay smaer
"tec ca" optmzatos suc as usg a faster programmg aguage.

Optma sortg
*Cogratuatos.* You ow ow about aayzg t e compexty of
agort ms, asymptotc be avor of fuctos ad bg-O otato. You
aso ow ow to tutvey fgure out t at t e compexty of a
agort m s O( 1 ), O( og(  ) ), O(  ), O( ^2 ) ad so fort . You
ow t e symbos o, O, , ad ad w at worst-case aayss meas. If
you've come t s far, t s tutora as aready served ts purpose.
T s fa secto s optoa. It s a tte more voved, so fee
free to sp t f you fee overw emed by t. It w requre you to
focus ad sped some momets worg t roug t e exercses. However, t
w provde you wt a very usefu met od  agort m compexty
aayss w c ca be very powerfu, so t's certay wort uderstadg.
We ooed at a sortg mpemetato above caed a seecto sort. We
metoed t at seecto sort s ot optma. A /optma agort m/ s
a agort m t at soves a probem  t e best possbe way, meag
t ere are o better agort ms for t s. T s meas t at a ot er
agort ms for sovg t e probem ave a worse or equa compexty to
t at optma agort m. T ere may be may optma agort ms for a
probem t at a s are t e same compexty. T e sortg probem ca be
soved optmay  varous ways. We ca use t e same dea as wt
bary searc to sort qucy. T s sortg met od s caed /mergesort/.
To perform a mergesort, we w frst eed to bud a eper fucto
t at we w t e use to do t e actua sortg. We w mae a |merge|
fucto w c taes two arrays t at are bot aready sorted ad merges
t em toget er to a bg sorted array. T s s easy doe:
|01.||def| |merge( A, B ):|
|02.|| ||f| |empty( A ):|
|03.|| ||retur| |B|
|04.|| ||f| |empty( B ):|
|05.|| ||retur| |A|
|06.|| ||f| |A[ ||0| |] < B[ ||0| |]:|
|07.|| ||retur| |cocat( A[ ||0| |], merge( A[ ||1.||..A_ ], B ) )|
|08.|| ||ese||:|
|09.|| ||retur| |cocat( B[ ||0| |], merge( A, B[ ||1.||..B_ ] ) )|
T e cocat fucto taes a tem, t e " ead", ad a array, t e "ta",
ad buds up ad returs a ew array w c cotas t e gve " ead"
tem as t e frst t g  t e ew array ad t e gve "ta" tem as
t e rest of t e eemets  t e array. For exampe, cocat( 3, [ 4, 5, 6
] ) returs [ 3, 4, 5, 6 ]. We use A_ ad B_ to deote t e szes of
arrays A ad B respectvey.

xercse 8
Verfy t at t e above fucto actuay performs a merge. Rewrte t 
your favourte programmg aguage  a teratve way (usg |for|
oops) stead of usg recurso.
Aayzg t s agort m reveas t at t as a rug tme of (  ),
w ere  s t e egt of t e resutg array ( = A_ + B_).

xercse 9

Verfy t at t e rug tme of |merge| s (  ).


Utzg t s fucto we ca bud a better sortg agort m. T e
dea s t e foowg: We spt t e array to two parts. We sort eac
of t e two parts recursvey, t e we merge t e two sorted arrays to
oe bg array. I pseudocode:
|1.||def| |mergeSort( A,  ):|
|2.|| ||f| | ||=| |1||:|
|3.|| ||retur| |A ||# t s aready sorted|
|4.|| ||mdde ||=| |foor(  ||/| |2| |)|
|5.|| ||eftHaf ||=| |A[ ||1.||..mdde ]|
|6.|| ||rg tHaf ||=| |A[ ( mdde ||+| |1| |)... ]|
|7.|| ||retur| |merge( mergeSort( eftHaf, mdde ), mergeSort(
rg tHaf,  ||-| |mdde ) )|
T s fucto s arder to uderstad t a w at we've goe t roug
prevousy, so t e foowg exercse may tae you a few mutes.

xercse 10
Verfy t e correctess of |mergeSort|. T at s, c ec to see f
|mergeSort| as defed above actuay correcty sorts t e array t s
gve. If you're avg troube uderstadg w y t wors, try t wt
a sma exampe array ad ru t "by ad". W e rug t s fucto
by ad, mae sure eftHaf ad rg tHaf are w at you get f you cut
t e array approxmatey  t e mdde; t does't ave to be exacty 
t e mdde f t e array as a odd umber of eemets (t at's w at
|foor| above s used for).
As a fa exampe, et us aayze t e compexty of |mergeSort|. I
every step of |mergeSort|, we're spttg t e array to two aves of
equa sze, smary to |barySearc |. However,  t s case, we
mata bot aves t roug out executo. We t e appy t e agort m
recursvey  eac af. After t e recurso returs, we appy t e
|merge| operato o t e resut w c taes (  ) tme.
So, we spt t e orga array to two arrays of sze  / 2 eac . T e
we merge t ose arrays, a operato t at merges  eemets ad t us
taes (  ) tme.
Tae a oo at *Fgure 7* to uderstad t s recurso.
N spts to N / 2 ad N / 2. ac of t ose spts to N / 4 ad N /
4, ad t e process cotues ut we ave cas of sze 1.
*Fgure 7*: T e recurso tree of merge sort.
Let's see w at's gog o ere. ac crce represets a ca to t e
|mergeSort| fucto. T e umber wrtte  t e crce dcates t e
sze of t e array t at s beg sorted. T e top bue crce s t e
orga ca to |mergeSort|, w ere we get to sort a array of sze .
T e arrows dcate recursve cas made betwee fuctos. T e orga
ca to |mergeSort| maes two cas to |mergeSort| o two arrays, eac
of sze  / 2. T s s dcated by t e two arrows at t e top. I tur,
eac of t ese cas maes two cas of ts ow to |mergeSort| two arrays
of sze  / 4 eac , ad so fort ut we arrve at arrays of sze 1.
T s dagram s caed a /recurso tree/, because t ustrates ow
t e recurso be aves ad oos e a tree (t e /root/ s at t e top
ad t e /eaves/ are at t e bottom, so  reaty t oos e a
versed tree).
Notce t at at eac row  t e above dagram, t e tota umber of
eemets s . To see t s, tae a oo at eac row dvduay. T e
frst row cotas oy oe ca to |mergeSort| wt a array of sze ,
so t e tota umber of eemets s . T e secod row as two cas to
|mergeSort| eac of sze  / 2. But  / 2 +  / 2 =  ad so aga 
t s row t e tota umber of eemets s . I t e t rd row, we ave 4
cas eac of w c s apped o a  / 4-szed array, yedg a tota
umber of eemets equa to  / 4 +  / 4 +  / 4 +  / 4 = 4 / 4 = .
So aga we get  eemets. Now otce t at at eac row  t s dagram
t e caer w ave to perform a |merge| operato o t e eemets
retured by t e caees. For exampe, t e crce dcated wt red
coor as to sort  / 2 eemets. To do t s, t spts t e  / 2-szed
array to two  / 4-szed arrays, cas |mergeSort| recursvey to sort
t ose (t ese cas are t e crces dcated wt gree coor), t e
merges t em toget er. T s merge operato requres to merge  / 2
eemets. At eac row  our tree, t e tota umber of eemets merged
s . I t e row t at we just expored, our fucto merges  / 2
eemets ad t e fucto o ts rg t (w c s  bue coor) aso as
to merge  / 2 eemets of ts ow. T at yeds  eemets  tota t at
eed to be merged for t e row we're oog at.
By t s argumet, t e compexty for eac row s (  ). We ow t at
t e umber of rows  t s dagram, aso caed t e /dept / of t e
recurso tree, w be og(  ). T e reasog for t s s exacty t e
same as t e oe we used w e aayzg t e compexty of bary searc .
We ave og(  ) rows ad eac of t em s (  ), t erefore t e
compexty of |mergeSort| s (  * og(  ) ). T s s muc better t a
( ^2 ) w c s w at seecto sort gave us (remember t at og(  ) s
muc smaer t a , ad so  * og(  ) s muc smaer t a  *  =
^2 ). If t s souds compcated to you, do't worry: It's ot easy t e
frst tme you see t. Revst t s secto ad reread about t e
argumets ere after you mpemet mergesort  your favourte
programmg aguage ad vadate t at t wors.
As you saw  t s ast exampe, compexty aayss aows us to
compare agort ms to see w c oe s better. Uder t ese
crcumstaces, we ca ow be pretty certa t at merge sort w
outperform seecto sort for arge arrays. T s cocuso woud be
ard to draw f we dd't ave t e t eoretca bacgroud of agort m
aayss t at we deveoped. I practce, deed sortg agort ms of
rug tme (  * og(  ) ) are used. For exampe, t e Lux ere
uses a sortg agort m caed eapsort
< ttp://xr.free-eectros.com/source/b/sort.c>, w c as t e same
rug tme as mergesort w c we expored ere, amey (  og(  ) )
ad so s optma. Notce t at we ave ot prove t at t ese sortg
agort ms are optma. Dog t s requres a sg ty more voved
mat ematca argumet, but rest assured t at t ey ca't get ay better
from a compexty pot of vew.
Havg fs ed readg t s tutora, t e tuto you deveoped for
agort m compexty aayss s oud be abe to ep you desg faster
programs ad focus your optmzato efforts o t e t gs t at reay
matter stead of t e mor t gs t at do't matter, ettg you wor
more productvey. I addto, t e mat ematca aguage ad otato
deveoped  t s artce suc as bg-O otato s epfu 
commucatg wt ot er software egeers w e you wat to argue about
t e rug tme of agort ms, so opefuy you w be abe to do t at
wt your ewy acqured owedge.

About
T s artce s cesed uder Creatve Commos 3.0 Attrbuto
< ttp://creatvecommos.org/ceses/by/3.0/>. T s meas you ca
copy/paste t, s are t, post t o your ow webste, c age t, ad
geeray do w atever you wat wt t, provdg you meto my ame.
At oug you do't ave to, f you base your wor o me, I ecourage
you to pubs your ow wrtgs uder Creatve Commos so t at t's
easer for ot ers to s are ad coaborate as we. I a smar
fas o, I ave to attrbute t e wor I used ere. T e fty cos t at
you see o t s page are t e fugue cos
< ttp://p.yusueamyamae.com/>. T e beautfu strped patter t at you
see  t s desg was created by Lea Verou
< ttp://eaverou.me/css3patters/>. Ad, more mportaty, t e
agort ms I ow so t at I was abe to wrte t s artce were taug t
to me by my professors Nos Papaspyrou
< ttp://www.softab.tua.gr/%7ce/> ad Dmtrs Fotas
< ttp://www.softab.tua.gr/%7fotas/>.
I'm currety a cryptograp y P D caddate at t e Uversty of At es
< ttp://d.uoa.gr/>. W e I wrote t s artce I was a udergraduate
ectrca ad Computer geerg < ttp://ece.tua.gr/> udergraduate
at t e Natoa Tec ca Uversty of At es < ttp://tua.gr/>
masterg  software < ttp://www.csab.tua.gr/> ad a coac at t e
Gree Competto  Iformatcs < ttp://pdp.gr/>. Idustry-wse I've
wored as a member of t e egeerg team t at but devatART
< ttp://www.devatart.com/>, a soca etwor for artsts, at t e
securty teams of Googe < ttps://www.googe.com/> ad Twtter
< ttps://twtter.com/>, ad two start-ups, Zo ad Kambu w ere we dd
soca etworg ad vdeo game deveopmet respectvey. Foow me o
Twtter < ttp://www.twtter.com/doyzz> or o GtHub
< ttp://gt ub.com/doyzz> f you ejoyed t s, or ma me
<mato:doyzz@gma.com> f you wat to get  touc . May youg
programmers do't ave a good owedge of t e gs aguage. -ma
me f you wat to trasate t s artce to your ow atve aguage
so t at more peope ca read t.
*T as for readg.* I dd't get pad to wrte t s artce, so f you
ed t, sed me a e-ma <mato:doyzz@gma.com> to say eo. I
ejoy recevg pctures of paces aroud t e word, so fee free to
attac a pcture of yoursef  your cty!

Refereces
1. Corme, Leserso, Rvest, Ste. Itroducto to Agort ms
< ttp://www.amazo.co.u/Itroducto-Agort ms-T-Corme/dp/0262533057/ref=
sr_1_1?e=UTF8&qd=1341414466&sr=8-1>,
MIT Press.
2. Dasgupta, Papadmtrou, Vazra. Agort ms
< ttp://www.amazo.co.u/Agort ms-Sajoy-Dasgupta/dp/0073523402/ref=sr_1_1
?s=boos&e=UTF8&qd=1341414505&sr=1-1>,
McGraw-H Press.
3. Fotas. Course of Dscrete Mat ematcs < ttp://dscrete.gr/> at t e
Natoa Tec ca Uversty of At es.
4. Fotas. Course of Agort ms ad Compexty
< ttp://www.coreab.ece.tua.gr/courses/agort ms/> at t e Natoa
Tec ca Uversty of At es.
Tweet
< ttps://twtter.com/s are> A btco
Doate va btco < ttp://btco.org/>:
Creatve Commos 3.0
< ttp://creatvecommos.org/ceses/by/3.0/>
Lovgy made  At es cty by doyzz < ttp://twtter.com/doyzz>.

Вам также может понравиться