Computer Science 15-112, Fall 2011
Class Notes: Efficiency
- Required
Reading
- Big-Oh
-
Common Function Families
-
Efficiency
-
The Big Idea
- Examples
Efficiency
- Required
Reading
- Wikipedia page on
Big-Oh Notation (you may gloss over the formal details!)
- Big-Oh
- Describes asymptotic behavior of a function
- Informally (for 15112): ignore all lower-order terms and
constants
- Formally (after 15112):
see here
- A few examples:
- 3n2 - 2n + 25 is O(n2)
- -30000n2 + 2n - 25 is O(n2)
- 0.00000000001n2 + 123456789n is O(n2)
- 10nlog17n + 25n - 17 is O(nlogn)
- Common Function Families
- Common Function Families (in increasing size)
- Constant (k)
- Logarithmic (logkn)
- Square-Root (n0.5)
- Linear (kn)
- Linearithmic, Loglinear, or quasilinear (nlogn)
- Quadratic (kn2)
- Exponential (kn)
- Graphically
(Images borrowed from
here)
- Efficiency
- When we say the program runs in O(f(n)), we mean...
- n is the size of our input
- f(n) = resource consumption of our program
- time, space, bandwidth, ...
- For 15112, we mainly care about time
- For time, we usually measure algorithmic steps rather than elapsed
time
(These share the same big-oh, but algorithmic steps are easier to
precisely describe and reason over)
- Count steps in a written algorithm, or comparisons and swaps in a
list, etc
- Can time your code's execution with: time.time()
- The Big Idea
- Each function family grows much faster than the one before
it!
- And: on modern computers, any function family is usually efficient
enough on small n, so we only care about large n
- So... Constants do not matter nearly as much as function
families
- Practically...
- Do not prematurely or overly optimize your code
- Instead: think
algorithmically
- Examples
- isPrime versus
fasterIsPrime
- linear search versus binary search
- Definitions
- Linear search: check each element in turn
- Binary search: check middle element, eliminate half on
each pass
- Number-guessing game
- Find a value in a sorted list (if we knew about lists...)
- Find a root (zero) of a function with bisection (really just binary
search)
- selectionsort versus mergesort
- See David Eck's most-excellent
xSortLab
- Also see these fun dancing-based visualizations of
selectionsort and
mergesort
- Definitions
- selectionsort: repeatedly select largest remaining element and
swap it into sorted position
- mergesort: sort blocks of 1's into 2's, 2's into 4's, etc,
on each pass merging sorted blocks into sorted larger blocks
- Analysis (in class)
- From lab2: isPrime(nthHappyNumber(n))
carpe diem -
carpe diem - carpe diem - carpe diem
- carpe diem - carpe diem -
carpe diem - carpe diem - carpe
diem