Lecture 3.1
Lecture 3.1
&
Complexity Analysis
6
Want to achieve platform-independence
11
Running Time of an Algorithm
• Running time is measured in terms of number of
steps/primitive operations performed
N = 10 => 53 steps
N = 100 => 503 steps
N = 1,000 => 5003 steps
N = 1,000,000 => 5,000,003 steps
f(N) = O(g(N))
10 n2 Vs n3 2500
10 n^2
2000
n^3
1500
1000
500
0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Comparing Functions
• As inputs get larger, any algorithm of a
smaller order will be more efficient than an
algorithm of a larger order
0.05 N2 = O(N2)
Time (steps)
3N = O(N)
N = 60 Input (size)
100n2 Vs 5n3, which one is
better?
250000
200000
150000
100000
50000
0
1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3
1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4
100n2 10 40 90 16 25 36 49 64 81 10 12 14 16 19 22 25 28 32 36 40 44 48 52 57 62 67 72 78 84 90 96 1E 1E 1E
5n3 5 40 13 32 62 10 17 25 36 50 66 86 10 13 16 20 24 29 34 40 46 53 60 69 78 87 98 1E 1E 1E 1E 2E 2E 2E
19
Common Orders of Growth
Let N be the input size, and b and k be constants
Increasing Complexity
O(logbN) = O(log N) Logarithmic Time
O(N) Linear Time
O(N log N)
O(N2) Quadratic Time
O(N3) Cubic Time
...
O(kN) Exponential Time
20
Size does matter[1]
What happens if we double the input size N?
N log2N 5N N log2N N2 2N
8 3 40 24 64 256
16 4 80 64 256 65536
32 5 160 160 1024 ~109
64 6 320 384 4096 ~1019
128 7 640 896 16384 ~1038
256 8 1280 2048 65536 ~1076
Size does matter[2]
• Suppose a program has run time O(n!) and
the run time for
n = 10 is 1 second
if (condition)
statement1;
else
statement2;
where statement1 runs in O(N) time and statement2
runs in O(N2) time?
31