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

TipsonAnalyzingtheTimeComplexityofAlgorithmsthatuseNestedLoops

Ifyouhavenestedloops,andtheouterloopiteratesitimesandtheinnerloop
iteratesjtimes,thestatementsinsidetheinnerloopwillbeexecutedatotalofi*j
times.Thisisbecausetheinnerloopwilliteratejtimesforeachoftheiiterationsof
theouterloop.

Thismeansthatifboththeouterandinnerlooparedependentontheproblemsize
n,thestatementsintheinnerloopwillbeexecutedO(n2)times:

for ( int i = 0; i < n; i++ ) {


for ( int j = 0; j < n; j++ ) {
// these statements are executed O(n2) times
}
}

for ( int i = 0; i < n / 2; i++ ) {


for ( int j = 0; j < n / 3; j++ ) {
// these statements are also executed O(n2) times
// since both loops loop O(n) times, and
// O(n) * O(n) = O(n2)
}
}

Similarly,ifyouhavetriplynestedloops,allofwhicharedependentontheproblem
sizen,thestatementsintheinnermostloopwillbeexecutedO(n3)times:

for ( int i = 0; i < n; i++ ) {


for ( int j = 0; j < n; j++ ) {
for ( int k = 0; k < n; k++ ) {
// these statements are executed O(n3) times
}
}
}

However,imagineacasewithdoublynestedloopswhereonlytheouterloopis
dependentontheproblemsizen,andtheinnerloopalwaysexecutesaconstant
numberoftimes,say3times:

for ( int i = 0; i < n; i++ ) {


for ( int j = 0; j < 3; j++ ) {
// these statements are executed O(n) times
}
}

Inthisparticularcase,theinnerloopwillexecuteexactly3timesforeachofthen
iterationsoftheouterloop,andsothetotalnumberoftimesthestatementsinthe
innermostloopwillbeexecutedis3norO(n)times,notO(n2)times.
Now,imagineathirdcase:youhavedoublynestedloops,andtheouterloopis
dependentontheproblemsizen,buttheinnerloopisdependentonthe
currentvalueoftheindexvariableoftheouterloop:

for ( int i = 0; i < n; i++ ) {


for ( int j = 0; j < i; j++ ) {
// these statements are executed O(n2) times
}
}

Let'sanalyzethiscaseiterationbyiteration:
Onthe1stiterationoftheouterloop(i=0),theinnerloopwilliterate0times
Onthe2nditerationoftheouterloop(i=1),theinnerloopwilliterate1time
Onthe3rditerationoftheouterloop(i=2),theinnerloopwilliterate2times
.
.
OntheFINALiterationoftheouterloop(i=n1),theinnerloopwill
iteraten1times

So,thetotalnumberoftimesthestatementsintheinnerloopwillbeexecuted
willbeequaltothesumoftheintegersfrom1ton1,whichis:

((n1)*n)/2=n2/2n/2=O(n2)times

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