Академический Документы
Профессиональный Документы
Культура Документы
Ifyouhavenestedloops,andtheouterloopiteratesitimesandtheinnerloop
iteratesjtimes,thestatementsinsidetheinnerloopwillbeexecutedatotalofi*j
times.Thisisbecausetheinnerloopwilliteratejtimesforeachoftheiiterationsof
theouterloop.
Thismeansthatifboththeouterandinnerlooparedependentontheproblemsize
n,thestatementsintheinnerloopwillbeexecutedO(n2)times:
Similarly,ifyouhavetriplynestedloops,allofwhicharedependentontheproblem
sizen,thestatementsintheinnermostloopwillbeexecutedO(n3)times:
However,imagineacasewithdoublynestedloopswhereonlytheouterloopis
dependentontheproblemsizen,andtheinnerloopalwaysexecutesaconstant
numberoftimes,say3times:
Inthisparticularcase,theinnerloopwillexecuteexactly3timesforeachofthen
iterationsoftheouterloop,andsothetotalnumberoftimesthestatementsinthe
innermostloopwillbeexecutedis3norO(n)times,notO(n2)times.
Now,imagineathirdcase:youhavedoublynestedloops,andtheouterloopis
dependentontheproblemsizen,buttheinnerloopisdependentonthe
currentvalueoftheindexvariableoftheouterloop:
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