Big O
Example
statement1; // runtime = 1 for (int i = 1; i <= N; i++) { // runtime = N^2 for (int j = 1; j <= N; j++) { // runtime = N statement2; } } for (int i = 1; i <= N; i++) { // runtime = 3N statement3; statement4; statement5; } // total = N^2 + 3N + 1
The actual constant does not matter --- remember that we haven't even specified how much a unit of time is --- so we get rid of constants:
N^2 + 3N + 1 --> N^2 + N + 1
Only the biggest power of N matters:
N^2 + N + 1 --> N^2
N^2 + N + 1 < 2N^2when N is big, and we already said we don't care about constants
O(N^2)
runtime.Finding Big O
What is the Big O?
int sum = 0; for (int i = 1; i < 100000; i++) { for (int j = 1; j <= i; j++;) { for (int k = 1; k <= N; k++) { sum++; } } } Vectorv; for (int x = 1; x <= N; x += 2) { v.insert(0, x); } cout << v << endl;
Complexity class: a category of algorithmic efficiency based on the algorithm's relationship to the input size "N".
Example complexity classes
Class | Big-Oh | If you double N, ... | Example |
---|---|---|---|
constant | O(1) | unchanged | 10ms |
logarithmic | O(log_2 N) | increases slightly | 175ms |
linear | O(N) | doubles | 2.1 sec |
log-linear | O(N log_2 N) | slightly more than doubles | 9 secs |
quadratic | O(N^2) | quadruples | 1 min 42 secs |
quad-linear | O(N^2 log_2 N) | slightly more than quadruple | 8 mins |
cubic | O(N^3) | multiplies by 8 | 55 mins |
... | ... | ... | ... |
exponential | O(2^N) | multiplies drastically | 5*10^61 years |
factorial | O(N!) | multiplies drastically | 10^200 years |