ex. division is much slower than addition.
ex. accessing different parts of memory takes different time.
For most of us, doing addition is much faster than multiplication.
But...
The teacher offers two types of homework
addtion v.s. multiplication
Assume that it takes 5 secs for you to do an addition problem and 20 secs for a multiplication problem.
Solution 1 takes
Solution 2 takes
If n is small, ex n = 3 solution 2 is better
What if n is large ? ex. n = 365
We say that the growth(complexity) of operations needed of the solution is higher.
So for the large n, we should choose solution 1
Precisely, the growth of function
which one is bigger ?
if is close to 0 when n close to inf., we say that f(n) less than g(n)
if it is close to inf. then n close to inf., we say that f(n) is larger than g(n). (not presicely)
We assume all operations take the same time.
We calculate the numbers of operations and
check its complexity and measure runtime.
ex.
now computation power of a computer is generally
the upper bound of complexity
Suppose the real time function is g(n)
then as
Usually we take the "tight" upper bound.
the rigorous upper bound of f(n)
Suppose the real time function is g(n)
then as
the lower bound of f(n)
the strict lower bound of f(n)
the strict upper bound and strict lower bound of f(n)
When analyzing complexity, we consider the worst case
Even the probability of it isn't large.
from 1 ~ n, take the i-th element
move it to the correct position
ex. sorting [3, 2 ,1 ,4]
for i from 1 to n
for j from i-1 to 1
if( seq[j] < seq[i])
switch seq[j] and seq[i]
else
breakex. sorting [3, 2 ,1 ,4]
Already sorted
ex. [1, 2, 3, 4, 5]
O(n)
Reverse Order
ex. [5, 4, 3, 2 ,1]
(n, n-1, n-2, ... 1)
If an algorithm has high space complexity and low time complexity.
Another one has low space complexity and high time complexity.
Which to choose?
when range large/small ? input size large/small?