So I have this count algorithm from the book Algorithms 4th edition that is used in the chapter of analysis of algorithms in which they calculate the frequency of each loop, if statement in the inner loop and from the declarations at the beguinning.
Each part they divide it in part A,B,C,D and E. They said that each one has the following frequency:
E = X (depends on input)
D = (N^3)/6 - (N^2)/2 + N/3
C = (N^2)/2 - N/2
B = N
A = 1
I know that all this frequencies come from partial sums, but I dont understant yer how they came to each answer, I would appreciate if someone could explain me why each frequency is like that.
public static int count(int[] a)
{
int N = a.length; // Part A
int cnt = 0; // Part A
for(int i = 0; i < N; i++) //Part A
for(int j = i+1; j < N; j++) // Part B
for(int k = j+1; k < N; k++) // Part C
if(a[i] + a[j] + a[k] == 0 // Part D
cnt++; // Part E
return cnt;
}
Part A should be obvious: the first three lines execute once.
Part B (the body of the outer loop) executes once for each iteration of the outer loop, for a total of N
times.
Part C (the body of the second loop) executes N - i - 1
times for each iteration of the outer loop, where i
varies from 0 to N-1
. When you add up sum(i
=0..N
-1){i
} you get N*(N-1)/2
or (N^2)/2 - N/2
.
Part D (the body of the third loop) executes i - j - 1
times for each iteration of the second loop, where i
varies from 0 to N-1
as before and j
varies from 0 to i - 1
. When you add that double sum up, you get the result for D.
Part E (the body of the if
statement) executes anywhere from 0 (e.g., all the a[i]
values are positive) to D times (e.g., all the a[i]
values are zero). Thus you can set bounds on X but cannot say more without making some assumptions about the input.