Experimental Studies
Experimental Studies
If an algorithm has been implemented. we can study its running time by executing
ii on various 1esL inputs and recording !he rime spent during each execution. A
simple approach for doing Lhis in Python is by using Lhe time function of Lhe time
module. This function reports !he number of seconds. or fractions !hereof. !hat ha\'e
elapsed since n benchmn.d: Lime known as !he epoch. The choic,e of !he epoch is
not significanl 10 our goal. as we can determine Lhe tlapstd Lime by recording !he
time just before Lhe nlgonthm and the time just after the algorithm. and c-0mputing
their difference. as follow~:
from time import t ime
st.lrLtime = time( ) ff' record the starting time
run algorithm
end_time = time( ) # record the ending time
elapsed = end_time - starLtime :Ii compute the elapsed time
500
••••
,....
400
••
! •••
• •••• •
~ 300
E
i=
• •••
Cl:
C
g 200
::
a:
•• ••• •
100
••
0
• •
0 5000 10000 15000
Input Siu
- - - - - - - - - - - - - - worst~'lL~e time
U\'et'll{:C-Cllse lime?
- - - b~1-aisc time
A B C D E F C
Input Instance
Figure 3.2: The difference between bcM-case and won.1-c~e time. Ench bar repre-
sent!. the running time of some algorithm on a different pos.,iblc input.
3.2. The Seven Functions Used in This Book 115
Th e Constant Function
The simplest function we can thml. of ,s the co11stant fimction. This is the function.
/ (11) - C,
for some fixed con.-.1nnt c. such as c - 5. c - 27. or c - 2 10. Tim1 is. for any
argument 11 , the constant function / (11) :isMgns the value c. In other words. ii does
not mauer what the ,'lllue or n is: / (11) will always be equal to the consmnt value c.
Because we are most interested in integer functions, the mosl fundamental con-
stant function is g(n) = I. and this is the typical constant function we use in this
book. Note that nny olher constant function. f (n) = c. can be wri11en :u, a cons1ant
c limes g(n). Thal i,. / (11) = <'g(n} in this Cll!,C.
As simple n., it b . the con, taol Function i, u5eful in algorithm analysis. bccoul>c
ii chnrncteri1e, the number or , teps needed 10 do a bO'tic operation on u compu1er.
like adding two number... as\1g111ng a value to ,omc ,':lnoblc, or comp:mng 1wo
number...
We note that most handheld calculators have a button marked LOG. but this is
typicnlly for cnJculating the logarithm base- 10. not base-two.
Computing the logarithm function e.~actly for nny integer II involves the use
of calculus. but \\e can use an opproxim:njon that is good enough for our pur-
poses without calculi.I!,. In particular. we con eru.ily compuie the l>malles1 integer
greater than or equal 10 logi,11 (its so-called ctili11g . r1ogi, 111). For positive integer.
11 . this value is equal to the number of times we can divide II by b before we ge1
u number less than or equal 10 I. For exnm pie. the evaluation of pog, 271 is 3.
becau1,e ((27/ 3)/3)/3 = I. Like\\1-.C. Po~ 64l i, 3. because ((64/ 4)i4)/4 = I.
and pog 2 121 is 4. becnu~e ((( 12/ 2)/2)/2)/2 = 0.75 ~ I.
TI1e following proposition de..cribes M:\.erol important identities thot involve
logarithms for nny bnse greater than I.
Proposition 3.1 ( Logarithm Rules) : Gncn n:al numbe~ a > O. b > I. c > 0
tmd d> I. we hmc:
I. lng11 (a<') - log,,a+ log1,r
2. log1,(t1/ t·) log1,a lng1,r
3. log11 (if) c IOgt,a
4. log1,a logJa/ logdh
5. 1,ktf,li ll~'l.th
By convention, the unpnren1he\lLCd notntion log11' denote.~ the value log(11' ).
We u,e a noiational i.honhand. log' 11. 10 denote the quantity. (log11)'. in which the
rcl>ult of the logarithm i\ rru,cd 10 o f)O\\ er.
The above idcntitie1, can be derived from COll\er.e rulci. for cxponcn1iation 1hm
we will prc,ent on page 121. We illustrate these 1demi11es with a few examples.
Example 3.2: \Ve dcmom.trotc below 1-omc mtcre\tmg 11pplic:itiom of !he /og11-
rithm ru/t!!> from Propo!>1tion 3. 1 (U!>W8 tl1e w,ual com ent,on that the ba.~e of 11
/ogllrirhm if> 1 if II i1, onutted).
• log(211) = log2 + log11 = I + log 11. by rule I
• log(11/ 2) =log11 - log2 - log11 - I. by rule 1
• log,,3 =31ogn. by rule 3
• log2" =111og2 =11 • l = 11, by rule 3
• lo&.i 11 = (log11)/log4 = (log11)/2. by rule 4
• 21ot11 = 11101! 2 = 11 1 = 11. by rule 5.
As:, proctical matter. we note tl1:1t rule 4 gfres us a way to compute the base-two
logarit11m on a calculator dmr has D b:Jse- 10 logarithm button. LOG. for
T he Linea r Function
Another simple yet important function is the li11ear f um:tum .
/ (11) = II.
That is. given an input value 11. lhe linear function/ assigns the value fl itself.
This function arises in algorithm analysis any time we have 10 do a single basic
operation for each of II elemenis. For example. comparing a number x to each
element of a sequence of size II wiU require II comparisons. The linear function
also represents the best running time we can hope to achieve for any algorith m that
processes each of II objects that are not already in the computer·s memory. because
rending in the" objects already requires fl operations.
T he N- Log-N Function
The next function we discuss in this section is the 11-log-11 f u11ctio11.
/ (11) = nlogn.
that is. the function that assigns to an input 11 the value of fl times the logarithm
base-two of n. This function grows a little more rapidly than the linear function and
a lot less rapidly than the quadratic function: therefore. we would greatly prefer an
algorithm with a running time that is proportional to II log11, than one with quadratic
running time. We will see several important algorithms that exhibit a running time
proportional to the 11-log-11 function. For example. the fastei."t possible algorithms
for sorting II arbitrary values require time proportional to II log 11.
T he Quadratic Function
Another function chat appears often in algorithm analysis is the qaadratic/ u11ctio11,
Thac is. given an input value fl. the function / assigns the produce of II wicb itself
(in other words, -,, squared").
The main reason why the quadratic function appears in the analysis of algo-
rithms is lhat there are many algorithms that have nested loops. where the inner
loop perfonns a linear number of operations and !he outer loop is performed a
linear number of limes. Thus, in such cases. the algorithm performs fl • 11 = fl 2
operations.
118 Chapter 3. Algorithm Analysis
In other words. this is the total number of operations that will be performed by the
nested loop if the number of operations performed inside the loop increases by one
with each iteration of the outer loop. This quantity also bns an interei.tiog history.
ln 1787. a German i,choolleacber decided 10 keep his 9- and I0-year-<>ld pupils
occupied by adding up tbc integers from I 10 I 00. Bui almoM immediately one
of the children claimed 10 have tbc ans\\er! The teacher was s~1>icious, for Lhe
s1udent had only the answer on his slate. But the answer. 5050. was correct and the
student. Carl Gauss. grew up to be one of the greatest mathematicians of his Lime.
We presume that young Gauss used the following identity.
Proposition 3.3: For any inreger 11 ~ I. \\ e h,we:
11 ( 11 + I}
1+2 -3 +··· - (n-2) - (n- l ) -'-11= - - -.
2
We give two "visual" ju.stifications of Proposition 3.3 in Figure 3.3.
n+t t - - - - - .
n n
3
2
O 23 n O 12n/2
(a) (b)
Figure 3.3: Visual justiticmions of Proposition 33. Both illustrations visualize the
identity in terms of the total area covered by " unit-width rec1angles will, heights
I, 2, ... . 11. In (a). the rec1angles arc shown to co,.er a big triangle of are.i 112 / 2 (base
11 and height 11) plus 11 ~mall tnangles of area I/ 2 each (base I and height I). In
(b). which applies onl) \\hen II is e,~n. the rectangles a.re shown 10 cover a big
rcctnngle of base n/ 2 and height n + I.
3.2. The Sc~cn Functions Used in This Book 119
The les!>on to be learned from Propos1Lion 3.3 is that if we perfonn :m algoriLhm
wiLh neltted loop<, such that the opemLioru. in the inner loop increase by one each
Lime. then Lhe total number or operations is quadratic in the number of times. 11.
we perfonn the ou1er loop. To be fair. the number or opera1ioru. is 112/ 2 + 11/ 2.
and :.o this is just over half the number of operations thnn nn algorithm that u~cs 11
operations each time the inner loop is perfom1ed. But the order or growth is still
quadratic in 11.
Polynomials
Mo:.t or the functions we ha,e h:.ted i.o far cun each be viewed as being part of a
larger clos!> of functions. the poly11omials. A polynomial fu nction has the fonn.
where no ,t1 1, ... ,ad are consLants. called the coefficients of the polynomial. and
flJfa 0. lnLeger d. which indicates the highest power in the polynomial. is called
the degree of the polynomial.
For example. the following funcLions are all pol) nomials:
• / {11)= 2 + 511 + 112
• /{11)= 1 + n1
• /{11) I
• /(11) "
• f{r,) - ,,2
Therefore. we could argue that thi., book presenLS J~t four important function!, u:,ed
in algorithm nnnlyi.i~. but ""e will , ticL. to saying that there are ..even. i.ince the con-
1,1an1. linear. and qundro11c funcuons are too important to be lumped in with other
polynomials. Running umei. Lhnt are polynomirus with small degree nre generally
beuer than polynomial running tin1es wi1h larger degree.
120 Chapter 3. Algorithm Analysis
Summations
A oouuion !hat appears again and again in the analysis of dam structures and algo-
rithms is the summation. which is defined as follows:
b
[ f (i) = f(a)-t- / (a- I )+ /{a ~2)+···+ f (b ),
' a
where a and b are integers and a ~ b. Summations arise in data i.tructure and algo-
rithm analysis because the running limes of loops naturally give ri~ 10 summations.
Using a summation. "'e can rewrite the fonnula of Proposition 3.3 as
f . 11(11 + 1)
1..., 1 - - - -
, I 2
Likewi!>e. we can \\.rite n polynomrnl / (11) of degreed" ith coef'ficienti. a 0, ... ,a,1 ru,
,I
/ (11) = [ a,11
1
•
I 0
Thu~. the summation notation givci, u~ n \honhand way of cxpres,ing , um, of in-
crca.,ing tenm that ha,e a regular structure.
/ {11) = II'.
where bis a positi\ e constant. called the base. and the argument II is the u po11mt.
That is. function / (11) assigns to the input argument II the value obtained by mul-
tiplying the base b by itself II times. As wru, the case ,, ith the logarithm function,
the most common base for the exponential function in algorithm analysis is b = 2.
For example. an integer word containing II bits can represent all the nonnegati ve
integers less than 1!'. If we have a loop that stfillS by perform.ing one operation
and the n doubles the nu mber of operations performed with each iteration. then the
number of operations performed in the d" iteration is 2".
We sometimes have other exponents besides n. however: hence. it is useful
for us to know a few bandy rules for working with exponents. In particular. the
following exponent rules are quite helpful
3.2. TIie Seven Functions Used in This Book 121
Proposition 3.4 (Exponent Rules): Gi\en positne integers". b. nnd c. we /wl'e
I. (It')' - If"
2. II' b' - II'.,.
3. If' /It - ba- ,
For example. we have the following:
=
• 256 = 162 = (2")2 z4 2 = 28 = 256 {Exponent Rule I)
• 243 = 35 = 3hJ = 3 23 3 = 9 •27 = 243 (Exponent Rule 2)
= = =
• 16 = 1024/ 64 2 10/ 26 2 10- 6 z4 = 16 (Exponent Rule 3)
We can extend the exponential function 10 exponents that arc fmc1ions or real
number. and 10 ncgauvc exponents. a.~ follow~. Given n positive i,ucgcr k, we de-
line 1, 1 4 10 be k'" root of b, 1h111 i~. 1he number r ,uch Lhlll I' - h. For cxomplc,
25 112 S, 1,incc 51 25. Like" t'>I!, 27 1 ' 3 and 16 1 ~ 2. This approach al-
lows u~ 10 define any power whose exponent can be exprc,sed n.~ u fraction, for
11'11 - (/1') 1 'c, by Exponent Rule I. For example, 9 1 2 = {9 1 ) 112 729 112 27.
Thus, If'/ ' is really jus1 the~ root or the integral exponen1 ll'.
We can further extend the exponc.ntinl funcuon 10 define b' for any real number
:c, by computing a !.Cries or numbers of the fonn II'' for fractions a/ c that get pro-
grcs!.ivcly clo!.Cr and clo~er 10:c. Any real number :c cnn be approximated orbi1mrily
closely by a rroc1ion a/c: hence. we can use the fraction a/ ca., 1he exponent of b
10 ge1 arbitrarily close 10 b'. For example. the number 211 is well defined. Finally.
given a negative c,poncnl ti. we define It' - 1/ b J. which correspond~ 10 applying
Exponent Rule 3 \\ ith a - 0 and c - - d. For example. 2 ' - I/ 21 - I/ 8.
Geometric Sums
Suppose we have a loop for which each iteration takes a multiplicative factor longer
than the previous one. This loop can be analyzed using the foUowing proposition.
Proposition 3.5: For any integer 11 ~ 0 and any real number a suc/J 111111 a > 0 and
a I I• consider the summation
"
L a' = I + a+ a1 + ·•·+ a"
j 0
- 0 - N -Lor,•N
+ -+~+-.......-----------ii---.C-:::---r---,.-,,,.ec;....t--+-___;.-1- l.mr:,r
- 1...op:ithmic
- cODStruJt
"
Figure 3.~: Growth rates for the se,en fundamental functions used in algorithm
analysis. We use base a = 2 for the exponential function. The functions are plotted
on a log-log chan. 10 compare the growth rates primarily as sl~. faen so. the
exponential function grows too fast 10 display all iu \.-alues on the chan.