5 Algorithm Analysis
5 Algorithm Analysis
N × (N + 1)
2
Ah, well, at least your solution is still correct, maybe not as fancy as your
partner’s.
In a dramatic twist of events, the teacher decides to actually run your program
on the computer, with N = 1010 .
You watch in pain as your program gets stuck for almost a minute before finally
throwing out 50000000005000000000 ; Your partner’s formula converted to code
outputs the same value instantly.
1
formular, it should be clear that given N as input, it takes 3 operations to
compute the required sum. This is the fundamental idea of algorithm analysis.
You count the number of steps your program takes to execute, and try to figure
out how it grows as your input becomes larger.
You are given an array A of size N , and then asked Q questions, each of which
gives two indices, i and j, such that 0 ≤ i ≤ j < N .
For each question, you have to find the sum Ai + Ai+1 + · · · + Aj .
Take a minute to think about your solution.
.
.
.
2
PQ
So, giving up our exact formula for the number of steps, k=1 (jk − ik + 1) and
trading it in for an upper bound, Q × N , actually gives us much more useful
information (here the takeaway is that our algorithm is too slow).
This is an important principle of algorithm analysis; we dump the exact formu-
lae, and try to get some idea of how the algorithm performs as the input size
increases.
3 Big-O notation
Often, as in the solution in sub-section 2.1, we replace the exact formula for the
number of steps an algorithm takes, and replace it by an upper bound.
So instead of j − i + 1, where j and i are part of questions, we instead note that
j − i + 1 ≤ N , and hence N is a suitable replacement.
This is also written as j − i + 1 = O(N ), and read as j − i + 1 is Big-O of N .
Now it would be rather useless to define a new symbol just to say that j −i+1 ≤
N ; so we ask the following question.
1 there is an additional technicality we are ignoring, feel free to read the correct definition