Two Factors:
What is “Best”? \text{Complexity} = \text{Time Complexity} + \text{Space Complexity}
Example: Two implementations of the sum formula
\text{Sum Formula: } \sum_{k = 1}^n k = 1 + 2 + 3 + ... + n
: Slow Sum Formula # A- O(n) # int sum = 0; for (int i = 1; i <= n; i++) += i; sum : Fast Sum Formula # B- O(1) # = n * (n + 1) / 2; sum
Professor’s Tangent:
- Q: How do you make an operation O(1)?
- A: Precompute the value and create a hash table!
We count the number of basic operations.
Example: Counting basic operations
int sum = 0; for (int i = 1; i<=n; i++) { for (int j = 1; i<=n; i++) { ++; sum} }
- The basic operation is
sum++;
- The algorithm is O(n^2)
\text{Efficiency (Best to Worst): }\\ 1 > \log n > n > n \log n > n^2 \land 2^n \land n! \\
Big O Notation: The upper bound on an algorithm’s running time.
Big \Omega Notation: The lower bound on an algorithm’s running time.
Big \Theta Notation: Used when the upper and lower bound of an algorithm’s running time is the same.
Remember: When improving algorithm efficiency, we’re concerned with improving O.
Example: Efficiency of bag ADT implementations
Operation Fixed Size Array Linked add
O(1) O(1) remove
O(1) O(1) clear
O(n) O(n) getFrequencyOf
O(n) O(n) contains
O(n) \land \Omega(1) O(n) \land \Omega(1) toArray
O(n) O(n) getCurrentSize
O(1) O(1)