Complexity
Complexity
Efficiency
A loop that does a fixed number of operations n times
is O(n)
worst-case: maximum number of operations for
inputs of given size
average-case: average number of operations for
inputs of given size
best-case: fewest number of operations for inputs of
given size
Computational Complexity
Linear Relationship
If t=cn, then an increase in the size of data increases the
execution time by the same factor
Logarithmic Relationship
logarithm n. Mathematics. The power to which a base, such as
10, must be raised to produce a given number
If t=log2n then doubling the size ‘n’ increases ‘t’ by one
time unit.
Asymptotic Complexity
26
Typical Complexities (2)
Complexity Notation Description
• Running time is usually the thing we care most about. But it can be as
well important to analyze the amount of memory used by a program. If
a program takes a lot of time, you can still run it, and just wait longer
for the result.
However if a program takes a lot of memory, you may not be able to
run it at all, so this is an important parameter to understand.
• We analyze things differently for recursive and iterative programs.
•
For an iterative program, it is usually just a matter of looking at the
variable declarations and storage allocation calls, e.g., array of n
numbers.
•
Analysis of recursive program space is more complicated: the space
used at any time is the total space used by all recursive calls active at
that time.
• Each recursive call takes a constant amount of space: some space for
local variables and function arguments, and also some space for
remembering where each call should return to.
Algorithm Efficiency, f(n)
A. Linear Logarithmic
1. i=1
2. loop (i <= 10)
1. j=1
2. loop (j <=10)
1. application code
2. j=jx2
3. end loop
4. i=i+1
3. end loop .:. f(n) = n log2 n
Nested Loops …
B. Quadratic
1. i=1
2. loop (i <= 10)
.:. f(n) = n2
1. j=1
2. loop (j <= 10)
1. application code
2. j=j+1
3. end loop
4. i=i+1
3. end loop
Big-O Notation (“on the order of”)
Picking midpoints;
Method 2 is actually like searching a binary tree, so we
will leave a full calculation until week 6, as right now the
maths could get complicated.
But for n=10, you should be able to calculate the average
case – try it! (When n=10 I make it 1.9 times as efficient)
Average Case Complexity
1i=1
2 loop (i <= n)
1j=1
2 loop (j <= n)
1k=1
2 loop (k <= n)
1 print (i, j, k)
2k=k+1
3 end loop
4j=j+1
3 end loop
4 i = i+1
3 end loop