The Efficiency of Algorithms

Two Factors:

  1. Time
  2. Space

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

# A: Slow Sum Formula
# - O(n)
int sum = 0;
for (int i = 1; i <= n; i++)
  sum += i;
# B: Fast Sum Formula
# - O(1)
sum = n * (n + 1) / 2;

Professor’s Tangent:

Counting Basic Operations

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++;
  }
}

Notation

\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)