1 3 Basics of Algorithm Analysis v4
1 3 Basics of Algorithm Analysis v4
Basics of
Algorithm Analysis
Ex 1:
83920
• # of bits → n = 17 bits
• # of digits → n = 5 digits Which are reasonable?
• Value: 83920 → n = 83920
Size of input instance
Ex 1:
83920
Ex 1:
83920
Ex 2:
10
14,23,25,30,31,52,62,79,88,98
• # of elements → n = 10
Is this reasonable?
Size of input instance
Ex 2:
10
14,23,25,30,31,52,62,79,88,98
● # of elements → n = 10 Reasonable
if each element has c bits, total number of bits is:
#bits = c * #elements
Time complexity is a function
Specifies how the running time depends on the size of the input
Function mapping
Worst instance
Worst-case running time. Consider the instance where the algorithm uses
largest number of basic operations
T(n) = number of basic operations the algorithm takes over the worst
instance of bit-size n
complexity
T(n)
input size n
Example
Algorithm 1:
x←100
For i=1...N
Time complexity:
j←j+1 ■ 2N +1 assignments
If x>50 then ■ N comparisons
x←x+3 ■ 2N additions
Total: 5N+1 basic operations
End If
End For
Asymptotic Order of Growth
Algorithm 2:
x←20 Time complexity
For i=1...N ■ N + 1 assignments
x←3x ■ N multiplications
Total: 2N+1 basic operations
End For
Upper bounds O
Informal: T(n) is O(f(n)) if T(n) grows with at most the same order of
magnitude as f(n) grows
T(n) = number of basic operations the algorithm takes over the worst
instance of bit-size n
complexity
T(n)
input size n
Asymptotic Order of Growth
Formal: T(n) is O(g(n)) if there exist constants ≥ 0 such that for all
≥ 0 we have.
T(n) ≤ c · g(n).
Intuitivamente, t ∈ O(g) indica que t está acotada superiormente por algún múltiplo
de g. Normalmente estaremos interesados en la menor función g tal que t
pertenezca a O(g)
Upper bounds - Cota Superior O
Propiedades de O
Veamos las propiedades de la cota superior. La demostración de todas ellas
se obtiene aplicando la definición formal.
, which is a constant
Asymptotic Order of Growth
Exercise 2:
■ T(n) = 2n+1, is it O(2n) ?
■ T(n) = 22n , is it O(2n) ?
Asymptotic Order of Growth
Exercise 2:
■ T(n) = 2n+1, is it O(2n) ? Yes
■ T(n) = 22n , is it O(2n) ? No
Solution 2 (second item): To have 22n < c.2n we need c>2n. So c is not.
Asymptotic Bounds for Some Common Functions
O(an)
O(nk)
O(n3)
O(n2)
O(n lg n)
O(n)
O(lg n)
O(1)
Informal: T(n) is Ω(g(n)) if T(n) grows with at least the same order of
magnitude as g(n) grows.
Formal: T(n) is Ω(g(n)) if there exist constants c>0 such that for all n we
have T(n) ≥ c·g(n).
■ Ω(n) ?
■ Ω(n2) ?
■ Ω(n3) ?
Lower Bounds - Cota Inferior Ω
● Ω(n) ? Yes
● Ω(n2) ? Yes
● Ω(n3) ? No
Tight Bounds - Cota Promedio Θ
Tight bounds. T(n) is Θ(g(n)) if T(n) is both O(g(n)) and Ω(g(n)).
Formal: T(n) is Θ(g(n)) if there exist constants c>0 and d>0 such that for all n
we have
c·g(n) ≤ T(n) ≤ d·g(n)
d·g(n)
c·g(n)
Tight Bounds - Cota Promedio Θ
Definición Formal. Sea T: N→[0,∞). Se define el conjunto de funciones de
orden Θ (Theta) de g como:
Θ(T) = O(T) ∩ Ω(T)
o, lo que es igual:
Is T(n):
■ Θ(n2) ?
■ Θ(n) ?
■ Θ(n3) ?
Lower and Tight Bounds
Is T(n):
● Θ(n2) ? Yes
● Θ(n) ? No
● Θ(n3) ? No
Lower and Tight Bounds
Exercise: Show that log(n!) is Θ(n log n)
Lower and Tight Bounds
Answer:
■ First we show that log (n!) = O(n log n)
log (n!) = log n + log (n-1) + … log 1 < n. log n, since the log function is
increasing
● Ω(n) ? Yes
● O(n) ? No, there is no input where the complexity of the algorithm has order 2
● Ω(n3/2) ? No
Implication of Asymptotic Analysis
Hypothesis
■ Basic operations (addition, comparison, shifts, etc) takes at least
10ms and at most 50ms seconds (This is time unity = u )
Algorithms
■ Algorithm A executes 20n operations for the worst instance (O(n))
■ Algorithm B executes n2 operations for the worst instance (Ω(n2))
Conclusion
■ For a instance of size n, A spends at most 1000n ms
■ For the worst instance of size n, B spends at least 10 n2 ms
■ For n>100, A is faster than B in the worst case, regargless of
which operations they execute.
Allows us to tell which algorithm is faster (for large instances)
Notation
■ Be careful: Asymmetric:
– f(n) = 5n3; g(n) = 3n2
– f(n) = O(n3) = g(n)
– but f(n) ≠ g(n)
max ← a1
for i = 2 to n {
if (ai > max)
max ← ai
}
i = 1, j = 1
while (both lists are nonempty) {
if (ai ≤ bj) append ai to output list and increment i
else(ai ≤ bj)append bj to output list and increment j
}
append remainder of nonempty list to output list
Claim. Merging two lists of size k takes O(n) time (n=total size=2k).
Pf. After each comparison, the length of output list increases by 1.
Claim. Merging two lists of size n takes O(n) time.
Pf. After each comparison, the length of output list increases by 1.
O(n log n) Time
O(n log n) solution. Sort the time-stamps.Scan the sorted list in order,
identifying the maximum gap between successive time-stamps.
Quadratic Time: O(n2)
0 1 1 0 0 1 0 0
1 0 0 1 0 0 0 0
Algorithm:
For i=1...n-1
For j=i+1...n
For k=1...n
If (Si(k)=Sj(k)=1)
Return ‘There are not disjoint sets’
End If
End For
End For
End For
Return ‘There are disjoint sets’
Cubic Time: O(n3)
1. A complexidade de tempo do algoritmo é O(n3)?
2. A complexidade de tempo do algoritmo é Ω(n3) ?
Cubic Time: O(n3)
1. A complexidade de tempo do algoritmo é O(n3)? SIM
2. A complexidade de tempo do algoritmo é Ω(n3) ? SIM
“Bad” instance: all sets are equal to {n} => algorithm makes Ω(n3) basic
operations
Exponential Time
1. Independent set. Given a graph, find the largest independent set?
a. O(n2 2n) solution. Enumerate all subsets.
S* ← φ
foreach subset S of nodes {
check whether S in an independent set
if (S is largest independent set seen so far) update S*
←S
}
}
There are many different algorithms for solving the same problem
Showing that an algorithm is Ω(n3) does not mean that we cannot find
another algorithm that solves this problem faster, say in O( 2)
Exercício
a)
sum = 0
Para i= 0 até n-1 faça
aux ← ai
Para j:=1 até i Análise: Número de operações
elementares é igual a:
aux ← x . aux
T(n) = 1+2+3+ … + n-1 = n(n-1)/2 = O(n2)
Fim Para
sum ← sum + aux
Fim Para
Devolva sum
Exercício - Solução
b)
sum = a0
pot = 1
Para i= 1 até n-1 faça Análise: A cada loop são realizadas O(1)
pot ← x.pot operações elementares. Logo, o tempo
sum ← sum + ai.pot é linear
Fim Para
Devolva sum
Recap
Point: We always consider worst instance, Omega(n) does not mean that all
instances take time ≥ ~ n
Observations on Ω( ( ))
Find closest pair of points, given input pairs (x1, y2),…,(xn, yn)
Function bin_search_main(x)
bin_search(1,n, x)
Binary Search Analysis
(the “sorting” slides has one slide that keeps the ceiling,
so you can see that it works)
Binary Search Analysis
T(n/2) c
T(n/4) log2n c
... ...
T(2)
c
c log2n
Binary Search Analysis
Proc Pot(x,n)
Se n=0 return 1
Se n=1 return x
Se n é par Análise:
tmp←Pot(x,n/2) T(n)= c+ T(n/2) => T(n) é O(log n)
Return tmp*tmp
Senão n é ímpar
tmp←Pot(x,(n-1)/2)
Return x*tmp*tmp
Fim Se
Fim