How may comparisons are done in the following algorithm ?
1 2 3 4 5 6 7 8 9 10 11 12 |
|
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
The outer-most loop will run n times as under;
1 s t time: and the inner-loop will run 1 time
2 n d time: and the inner-loop will run 2 times
3 r d time: and the inner-loop will run 3 times
4 t h time: and the inner-loop will run 4 times
.
.
.
( n − 1 ) t h time: and the inner-loop will run (n-1) times
n t h time: and the inner-loop will run n times
Hence the total number of comparisons done are 1+2+3+4+...+(n-1)+n= 2 n ( n + 1 ) .