Chapter 2
Chapter 2
Complexity Analysis
Algorithm Complexity
The same problem can frequently be solved with
different algorithms which differ in efficiency
Some algorithms require more space than others
Technically, you could always buy more memory
Some require more time
No easy solutions here: even the fastest CPU has a limit
Time is usually a more important constraint
Algorithm time efficiency is measured in logical units
rather than real-time units such as “milliseconds per
byte of data”
Algorithm time efficiency is determined by the
relationship between the size n of data to be processed
and the amount of time t required to process the data
c g(n)
f(n)
N n
Asymptotic Complexity: Big-O ❑ ❑
𝑙𝑜𝑔 𝑥=lg𝑥
2
1. f(n) =
Big-O: O()
2. f(n) = 1000000
Big-O: O()
3. f(n) = 2n +
Big-O: O()
4. f(n) = 10 + n + log n
Big-O: O(n)
5. f(n) = 10 + 364
Big-O: O()
3 • ank is O(nk)
int i = 0, j = 1; // 2 assignments
while(i < n) {
i++; // assignment
j += 2; // assignment
}
k = 0;
for(i = 0; i < n; i++)
for(j = 0; j < n; j++)
k++;
1 + 1 + n (1 + 1 + n(1 + 1))
Calculating Big-O: examples
Example 2: n
k = 0;
for(i = 0; i < n; i++)
for(j = 0; j < n; j++) n
k++;
1 + 1 + n (1 + 1 + n(1 + 1)) = 2 + 2n + 2
Complexity?
O()
Calculating Big-O: examples
Example 3:
O()
Calculating Big-O: examples
Example 4:
Complexity?
O(n)
Calculating Big-O: examples
Example 5:
1 + n(1 + 1 + n (1 + 1 + ()))
How many times will the innermost loop execute?
What is the Complexity?
O()
Calculating Big-O: examples
Example 6:
How many times will the
sum = 0, i = 9; while loop execute?
while(i < n) {
i++;
for(j = i – 8; j <= i; ++j)
sum++; How many times will the
for loop execute?
}
}
What is the Big-O
Complexity?
O(n)
Calculating Big-O: examples
Example 7:
Complexity is O()
int fib(n) {
if(n <= 1) return n; Is it good or bad?
else return fib(n-1) + fib(n-2);
}
It doesn’t get much
What is the complexity? worse than this!