my question is in the title. After hours of thinking and looking up sites on google i came to the conclusion that i'm not quite sure how to solve this problem or if it is correct. Maybe you guys could give me some advice to solve such things faster or in an easier way. Any help is appreciated!
The cost function of the algorithm is:
T(n) = O(n log n).
The outer loop is executed approximately log(n) times (because "i" is doubled in each iteration), and the inner loop is executed at most n times in each iteration of the outer loop (on the first iteration of the outer loop) and at most half as many times in each subsequent iteration of the outer loop. Together, this results in a runtime of O(n log n).
public float[] normalize (float[] seq) {
int n = seq.length;
float sum = 0;
int cnt = 0;
int i;
for (i = 1; i < n; i = i + i ) {
for ( int j = 0; j < i; j++) {
sum = sum + seq [j];
}
cnt += i;
}
float[] res = new float [n];
while (i >= 0) {
if (i < n) {
res [i] = seq[i] / (sum / cnt);
}
i--;
}
return res;
}
The cost function of the algorithm is:
T(n) = O(n log n).
The outer loop is executed approximately log(n) times (because "i" is doubled in each iteration), and the inner loop is executed at most n times in each iteration of the outer loop (on the first iteration of the outer loop) and at most half as many times in each subsequent iteration of the outer loop. Together, this results in a runtime of O(n log n).