Like the Big O notation “O(1)” can describe following code:
JavaScript
x
O(1):
for (int i = 0; i < 10; i++) {
// do stuff
a[i] = INT;
}
O(n):
for (int i = 0; i < n; i++) {
// do stuff
a[i] = INT;
}
O(n^2):
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// do stuff
a[i][j] = INT;
}
}
- What code can O(log(n)) describe?
Another question:
- What solutions are there for “Big O problems” (what to do, when getting a lot of data as an input)?
Advertisement
Answer
Classic example:
JavaScript
while (x > 0) {
x /= 2;
}
This will be:
JavaScript
Iteration | x
----------+-------
0 | x
1 | x/2
2 | x/4
|
|
k | x/2^k
2k = x → Applying log to both sides → k = log(x)