Ok so I\'m new to analyzing algorithms and would really appreciate any helpful tips that can be shared on how to go about this. I am trying to determine how many times count
Here you go:
count = n * (n + 1) / 2
The aim of this type of exercise is to teach how to you analyze it on paper instead of running it on a machine. But let's look at the pattern:
n
timesn
times depend on what i
is at the time. But you know that on average this will run (n+1)/2
times.count = n(n+1)/2)
, which is O(n^2)
See arithmetic series
Update: As requested - why the inner loop is (n+1)/2
:
The outer loop will increment i between 1 and n. So on each iteration of the outer loop, the inner loop will "loop" one more than than it did previously.
Thus the inner loop will iterate this number of times:
So we can do something clever and pair up :
And since we paired these up, we have n/2 such pairs:
(Visualize it as you are writing 1 + 2 + 3 + ... + n on a long strip of paper, and you fold it in half.)
I would also highly recommend reading this famous story about Karl Friedrich Gauss so you'll always remember how to sum arithmetic series =)
1
1+2 = 3
1+2+3 = 6
1+2+3+4 = 10
1+2+3+4+5 = 15
It is only me who sees the pattern? :-)