Efficiency of Algorithms Algorithms
Efficiency of Algorithms Algorithms
Efficiency of Algorithms Algorithms
1
Which is more useful? How to compare
• For real time programming: the worst case • Suppose we settle on comparing the worst case
• For getting a general idea of running time: average performance of linear and binary search.
case; however, often difficult to establish • Where do we start?
• For choosing between several available • Timing
algorithms: helps to know what is the best case • ...
(maybe your data are in the best case format, for
example random).
2
Basic operations Basic operations contd.
• Basic operations are operations which take • If we are not sure how operations are
constant time (at most time C for some constant implemented, we have to exercise judgement: can
C). something be in principle implemented as a
• In other words, time required to perform the constant time operation?
operation does not grow with the size of the • For example, adding two 32-bit integers can be,
operands, or is bounded by a constant. but adding a list of 32-bit integers can not: it is
going to take longer for a longer list.
3
O() complexity measure Upper bound example
f(N)=2N
Big O notation gives an asymptotic upper bound t(N)=3+N
on the actual function which describes
time/memory usage of the algorithm.
t(N) is in O(N)
The complexity of an algorithm is O(f(N)) if there because for all N>3,
exists a constant factor K and an input size N0 2N > 3+N
such that the actual usage of time/memory by the Here, N0 = 3 and
algorithm on inputs greater than N0 is always less K=2.
than K f(N).
N0 N
4
Practical hints Warning about O-notation
• Find the actual function which shows how the • O-notation only gives sensible comparisons of
time/memory usage grows depending on the input algorithms when N is large
N. Consider two algorithms for same task:
• Omit all constant factors. Linear: g(N) = 1000 N is in O(N)
Quadratic: g'(N) = N2/1000 is in O(N2 )
• If the function contains different powers of N,
(e.g. N4 + N3 + N2), leave only the highest power • The quadratic one is faster for N < 1 000 000.
(N4). • Some constant factors are machine dependent, but
• Similarly, an exponential (2N) eventually others are a property of the algorithm itself.
outgrows any polynomial in N.
Informal coursework
Which statements below are true?
• If an algorithm has time complexity O(N2), it
always makes precisely N2 steps, where N is the
size of the input.
• An algorithm with time complexity O(N) is
always runs slower than an algorithm with time
complexity O(log2(N)), for any input.
• An algorithm which makes C1 log2(N) steps and
an algorithm which makes C2 log4(N) steps
belong to the same complexity class (C1 and C2
are constants).