StringBuilder read while str = input.readline() read.append(str) for i = 0 to read.length() if read.charAt(i) == '<' // process tag
StringBuilder read while str = input.readline() read.append(str) for i = 0 to read.length() if read.charAt(i) == '<' // process tag read.setCharAt(i) = ' '
C*g(n) >= f(n)as n grows without bound for some positive constant C.
Constant O(1) hash table searching Log O(log n) binary search Linear O(n) linear search Log-linear 0(n log n) heapsort Quadratic O(n2) bubble sort Cubic O(n3) matrix multiplication Exponential O(2n) optimal route finding
f f(n) C C log n 4.6 n 100 n log n 460.5 n2 10,000 n3 1,000,000 2n 1,267,650,600,228,229,401,496,703,205,376
i = 0 while i < n j = i + 1 while j < n if a[i] > a[j] std::swap(a[i], a[j]) j++ i++
vec.size()
with lst.size()
.
i = 0 while i < n j = i + 1 while j < n if a[i] > a[j] std::swap(a[i], a[j]) j++ i++ |
O(1) while i < n O(1) while j < n if a[i] > a[j] O(1) O(1) O(1) |
if
statementif b s
1 else s
2
s
1 or s
2, but which one?
b
's cost.
if
ExampleO(1) while i < n O(1) while j < n if a[i] > a[j] O(1) O(1) O(1) |
O(1)
while i < n
O(1)
while j < n
O(1) + O(1) = O(1)
O(1)
O(1) |
s
1 ;
s
2
s
1 is O(f), s
2 is O(g), so s
1; s
2 is
O(f) + O(g)
O(1) while i < n O(1) while j < n O(1) O(1) O(1) |
O(1)
while i < n
O(1)
while j < n
O(1) + O(1) = O(max(1, 1)) = O(1)
O(1) |
while b do s
s
has asymptotic estimate O(f).
s
gets executed some number of times.
O(1) while i < n O(1) while j < n O(1) O(1) |
O(1)
while i < n
O(1)
O(n)*(O(1) + O(1)) = O(n)
O(1) |
O(1) while i < n O(1) O(n) O(1) |
O(1)
while i < n
O(1) + O(n) + O(1) = O(n) |
O(1) while i < n O(n) |
O(1)
O(n)*O(n) = O(n2)
|
O(1) O(n2) |
O(1) + O(n2) = O(n2) |
In the worst case, swap sort moves O(n2) elements when sorting an n-element array.
while vec.size() > 0 vec.erase(vec.end() - 1) while vec.size() > 0 vec.erase(vec.begin())