Average Case: The amount of time the algorithm takes on an "average" set of inputs.
Worst Case: The amount of time the algorithm takes on the worst possible set of inputs.
Size of input: We like to be able to express a program's running time as a function of the size of the input. The size of the input is typically denoted as N and the running time of the algorithm as T(N). By plugging in the size of the input, we can get a rough estimate of the cost of executing the algorithm.
1: The running time of the program is constant (i.e., it is independent of the size of the input).
Example: Find the 5th element in an array.
log N: Typically achieved by dividing the problem into smaller segments and only looking at one input element in each segment.
Example: Binary search
N: Typically achieved by examining each element in the input once
Example: Find the minimum element
N log N: Typically achieved by dividing the problem into subproblems, solving the subproblems independently, and then combining the results. Unlike the log N algorithms, each element in the subproblems must be examined.
Example: Merge sort
N^2: Typically achieved by examining all pairs of data elements.
Example: Selection Sort
N^3: Often achieved by combining algorithms with a mixture of the previous running times.
Example: Matrix Multiplication--Each item in the result matrix is obtained by multiplying together two vectors of size N. This requires N time. Since there are N^2 elements in the result matrix, it takes N^3 time to compute the entire result matrix.
| Recurrence | Solution |
| T(N) = T(N/2) + d | T(N) = O(log N) |
| T(N) = T(N/2) + N | T(N) = O(N) |
| T(N) = 2T(N/2) + d | T(N) = O(N) |
| T(N) = 2T(N/2) + N | T(N) = O(N log N) |
| T(N) = T(N-1) + d | T(N) = O(N) |
Machine time: Ultimately the best measure but subject to variation due to different instruction costs on different machines.
Abstract time: Abstract away from machines by using a model that assigns a cost of 1 to simple instructions, such as assignment or reading one input element. Using this simple cost, count the number of instructions and try to express this count as a function of the input size.
Big O Notation: Abstracts away all but the most significant cost term. In general, the most significant cost term will dominate the running time of the algorithm once input sizes get very large.
Example: 5N^2 + N + 20 is O(N^2).
Choose the simplest algorithm first and implement it. Consider a faster, but potentially more complicated, algorithm only if speed becomes a problem. Even if it is clear from the outset that a faster, more complicated algorithm is required, consider implementing a simpler algorithm as a way of checking the correctness of the more complicated algorithm.