Documente Academic
Documente Profesional
Documente Cultură
Fall 2020
Big O Analysis:
Quick Review
Example 1: Sequential/Linear Search
for (int i=0; i < arr.length; i++) {
if (target == arr[i]) { What operations to count?
return true; Loop mechanics Algorithm
} characteristic
} Comparing target
return false;
• Initializing i
• Checking i against against array item
array length (basic operation)
Analysis must relate count to • Incrementing i
array (input) length, say n
2 + 1= 3 2n + n = 3n
0 1 2 3 4 5 6 7
output 1 6 9 11 18 23 24 32
Initializing j 1 1
for (int j=0; j < output.length;
j++) { Checking j against array length 1 n+1
for (int i=0; i <= j; i++) { Incrementing j 1 n
output[j] += input[i];
} Initializing i 1 n
}
Checking i against array length 1 2+3+…(n+1)
Which means…..
1 + 2 + 3 + …. + (n-2) + (n-1)
(n-1)*((n-1)+1)
2
n*(n-1)
and… 2
(n+1)*(n+2)
- 1
2
Initializing j 1 1
Incrementing j 1 n
Initializing i 1 n
3n2/2 + 5n/2 + 2
CS 112 Fall '20: Big O Analysis 8
Example 3:
Partial Sums – Version 2
This is not included in the table Output length = Input length = n
since it’s an outlier. We’ll add 1 unit of
time for it at the end.
Operation Time How many
per
Initializing j 1 1
output[0] = input[0];
Checking j against array length 1 n
for (int j=1; j < output.length; Incrementing j 1 n-1
j++) {
output[j] = output[j-1] + Adding to array item 1 n-1
input[j];
}
Algorithm characteristic
Total Running Time:
Adding to array item
1 + n + (n-1) + (n-1) + 1 (outlier)
(basic operation)
= 3n
We boil running times down to the Order of Complexity, called “Big Oh”,
so we can classify according to order – O(n2) runs much slower than O(n),
for large enough n (so that edge effects are taken out of the equation)
Ignoring looping mechanism does NOT change the Big O (makes sense
because looping mechanism is just supporting scaffolding to execute the
algorithm, so it cannot supersede the algorithm’s running time.)