Design and Analysis of ALGORITHM (Week 2) : Our Machine Model: Assumptions
Design and Analysis of ALGORITHM (Week 2) : Our Machine Model: Assumptions
Notes:
Eliminates dependence on the speed of our computer,
otherwise impossible to verify and to compare
1
Running time
• The running time depends on the input.
Example: an already sorted sequence is easier to
sort.
• Major Simplifying Convention: Parameterize the
running time by the size of the input.
TA(n) = time of A on length n inputs
• Generally, we seek upper bounds on the running
time, to have a guarantee of performance.
Notes:
The running time of an algorithm is determined by its input size n
2
Time Complexity
The complexity of an algorithm is determined by the number of
basic operations and how many time the algorithm computes those
basic operations.
Purpose
To estimate how long a program will run.
To estimate the largest input that can reasonably be
given to the program.
To compare the efficiency of different algorithms.
To help focus on the parts of code that are executed the
largest number of times.
To choose an algorithm for an application.
3
Time Complexity: an example
Example:
Suppose a sorting algorithm has some inputs with a same size
but different order:
In ascending order
-Input 1: 10, 5, 23, 45, 1, 100 Average case
4
Best, Worst and Average Case (cont.)
Let In denote a set of all input with size n of an algorithm and (i)
denote the number of primitive operations of the corresponding
algorithm when given input i.
Mathematically, we can define:
5
Example of insertion sort
8 2 4 9 3 6
2 8 4 9 3 6
2 4 8 9 3 6
2 4 8 9 3 6
2 3 4 8 9 6
2 3 4 6 8 9 done
n
t 1
6 ii–1 c6 j 2 j
n = length(A)
6
Insertion Sort: an analysis
T (n) c1n c2 (n 1) c3 (n 1) c4 j 2 t j c5 j 2 (t j 1)
n n
c6 j 2 (t j 1) c7 (n 1)
n
7
Machine-independent time
“Asymptotic Analysis”
Analysis
Simplifications
Ignore actual and abstract statement
costs
Order of growth is the interesting
measure:
Highest-order term is what counts
Remember, we are doing asymptotic analysis
As the input size grows larger it is the high
order term that dominates
8
Assignment 1
In order to show that an algorithm is
not unique, design two different
algorithms of a specific problem.
Design an algorithm and show its
time complexity to compute a product
of two n x n matrices (how is the time
complexity in the best and worst
cases?)