Beruflich Dokumente
Kultur Dokumente
Implementation
• We can see
if there is at least one item in the collection
• Parameters: None
• Pre: True (i.e. there are no preconditions)
• Post: The empty stack S = [] is produced
push
Let T (n) be the running time of len when applied to a list of length
n (measured as the number of substitution steps required)
Solution: T (n) = a + bn
A quicker analysis:
• O(1) (constant)
• O(log n) (logarithmic)
• O(n) (linear)
• O(n log n) (loglinear)
• O(n2 ) (quadratic)
• O(2n ) (exponential)
2
c g(n) = 5n
f(n) = 3n2 + 2
n0 = 1 n
O(1) (Constant running time): cons, first, rest, empty?, and, or, not,
numeric compuations on bounded numbers, operations on
structures, operations on symbols
Best Case: For an input of size n, what contents of the input will
give the function its quickest running time?
It is incorrect to say that “the best case running time for a function is
O(1) when n=0” (running times must hold for all n)
Some functions have the same best and worst case running times;
here the contents of the input do not matter
16000 O(log2 n)
O(n)
O(n log2 n)
14000
O(n2)
O(n3)
12000
10000
8000
6000
4000
2000
0
50
1
0
10
15
20
25
30
35
40
45
50
55
60
65
CS 136 Winter 2011 01: Introduction to CS 136 35
Does it really work?
Jon Bentley describes an experiment in Programming Pearls, p. 75.
The problem is to take a list of N real numbers and return the
maximum sum found in any contiguous sublist. For example:
100
1,000
10,000
100,000
1,000,000
1,000 20 secs
10,000
100,000
1,000,000