Algorithms & Complexity - Introduction: Nicolas Stroppa - Nstroppa@computing - Dcu.ie
Algorithms & Complexity - Introduction: Nicolas Stroppa - Nstroppa@computing - Dcu.ie
Algorithms & Complexity - Introduction: Nicolas Stroppa - Nstroppa@computing - Dcu.ie
November 6, 2006
Introduction
Note
We thus make the assumption that each elementary instruction
takes the same amount of time (because it is probably one
processor instruction, which is true for example for addition and
multiplication between integers).
Introduction
Note
We thus make the assumption that each elementary object needs
the same amount of space (which is almost true for the basic
types: one machine word).
Introduction
Estimation/Prediction
When you write/run a program, you need to be able to predict its
needs, its requirements.
Usual requirements
I execution time
I memory space
Quantities to estimate
I execution time ⇒ time complexity
I memory space ⇒ space complexity
Introduction
It is very important that you know what you can and cannot
do to improve (i.e. optimize) your algorithms:
I It is not wise to run an algorithm with O(n2 ) complexity if
there is an algorithm with O(ln(n)) doing the same job. . .
I Do not try to optimize an algorithm for a problem if we
formally know there is no efficient (i.e. polynomial)
algorithm. . .
I ⇒ You will need to know how to compute and estimate the
complexity of algorithms if you want to be able to say that.
Introduction
You will read things like “C is faster than Java”, “Java is faster
than Python”, etc.
Note
An algorithm with complexity O(n × ln(n)) in Python will probably
be faster than an algorithm with complexity O(n2 ) in C. . .
Introduction
A formal definition
Definition (Time complexity)
We will note T (A, n) the number of elementary instructions that
an algorithm A executes when the size of the input data is n, or
T (A) when unambiguous.
Example
// note: x is an unsorted array
int findMin(int[] x) {
int k = 0; int n = x.length;
for (int i = 1; i < n; i++) {
if (x[i] < x[k]) {
k = i;
}
}
return k;
}
Introduction
Sequence of instructions
The number of elementary instructions executed in a sequence of
instructions is the sum of the number of elementary instructions
executed in each instruction:
Loop of instructions
The number of elementary instructions executed in a loop is (at
most) the number of iterations multiplied by the number of
elementary instructions executed in the body of the loop:
Example
// note: x is an unsorted array
int findMin(int[] x) {
int k = 0; int n = x.length;
for (int i = 1; i < n; i++) {
if (x[i] < x[k]) {
k = i;
}
}
return k;
}
T (findMin, n) = 2 + T (findMinLoop) × n + 1
T (findMinLoop) = 2
T (findMin, n) = 3 + 2 × n
Introduction
The O
The O - Examples
Worst-case complexity
Average complexity
1 X
Tav (n) = × T (i),
| In |
i∈In
I constant: O(1)
I logarithmic: O(ln(n))
I linear: O(n)
I quadratic: O(n2 )
I cubic: O(n3 )
I polynomial: O(np ), p ∈ N
I exponential: O(exp(n))
Introduction