tips: return;, a=1; should be counted when using T(N)
Asymptotic Notation
T(N)=O(f(N)),T(N)≤c⋅f(N),∀N>n0(smallest)
T(N)=Ω(g(N)),T(N)≥c⋅g(N),∀N>n0(largest)
T(N)=Θ(h(N)),T(N)=O(h(N))
T(N)=o(p(N)),ifT(N)=O(p(N))andT(N)=Θ(p(N))
[Eg1] Matrix addition
voidadd( int a[][ MAX_SIZE ], int b[][ MAX_SIXE ], int c[][ MAX_SIZE ], int rows, int cols){ int i,j; for( i = 0; i < cols; ++i){ for( j = 0; j < rows; ++j){ c[i][j] = a [i][j] + b[i][j]; } } }
T(rows,cols)=2rows⋅cols+2rows+1
O(rows,cols)=rows⋅cols
[Eg2] Summing a list of numbers (iterative)
floatsum( floatlist[], int n ){ float temp_sum = 0; // count = 1 int i; // no add count for( i = 0; i < n; ++i ){ // count += 1 temp_sum += list[i]; // count += 1 } return temp_sum; // count += 1 }
Tsum(n)=2n+3
[Eg3] Summing a list of numbers (recursive)
floatsum( floatlist[], int n ){ if( n ){ // count = 1 return sum( list, n-1 ) + list[n-1]; // count += 1 } return0; // count += 1 }
Tsum(n)=2n+2
Space complexity
Compare the Algorithms
[Eg] Max Subsequence Sum Problem Given integers A1, A2, …, An, find the maximum value of sum from Ai to Aj
Algo.1
for i: n for j: n sum for k: i->j compare sum
T(N)=O(N3)
Algo.2
for i: n for j: i->n sum i->j compare sum with max_sum
T(N)=O(N2)
Storing to cut off calculatation
Algo.3 ( Divide & Conquer )
def MSS( sequnce a[n], int start, int end ): if length <= 1 : return a[n] left = MSS (a, start, mid) right = MSS (a, mid, end) total = max_sum for mid->end + max_sum for mid->start return max( left, right, total )