Computer Science Notes

Notes From CS Undergrad Courses FSU

This project is maintained by awa03

Complexity Analysis

// number of outputs
// t(n) = n
for(i = 0; i < n, i++){
	cout << A[i] << endl;
}

// number of comparisons
// t(n) = n-1
template<class T>
bool IsSorted(T *A, int n){
	bool sorted = true;
	for(int i=0; i<n-1; i++){
		if(A[i]) > A[i+1]){
			sorted = false;
		}
	}
	return sorted;
}

Algorithm analysis covers the worst case (most of the time). The average case is more useful, however, it is more difficult to calculate. The complexity of a function is its input size. For instance... $t(n) = 1000n$ vs. $t(n) = 2n^2$ if n doubled... $t(n) = 1000n...$$1000*2n/1000n = 2$

Scaling Analysis

Example Problem

Algorithm 1: $t_1(n) = 100n+n^2$

Asymptotic Complexity Analysis

Big "O" Notation

$f(n)=O(g(n))$ $iff ∃ c, n_0 > 0 | 0 < f(n) < cg(n) ∀ n >= n_0$

Big "Omega" Notation

$f(n)=Ω(g(n))$ $iff ∃ c, n_0 > 0 | 0 < cg(n) < f(n) ∀ n >= n_0$

Big "Theta" Notation

$f(n)=θ(g(n))$ $iff ∃ c_1, c_2, n_0 > 0 | 0 < c_1g(n) < f(n) < c_2g(n) ∀ n >= n_0$

Examples

$f(n) = 3n^2 + 17$

$Ω(1), Ω(n), Ω(n^2)$ -> lower bounds

Transitivity

$f(n) = O(g(n))$ -> $(a <= b)$ $f(n) = Ω(g(n))$ -> $(a >= b)$ $f(n) = θ(g(n))$ -> $(a = b)$

Additive property

Function Name
c Constant
$log(N)$ Logarithmic
$log^2(N)$ Log-squared
N Linear
$N log N$
$N^2$ Quadratic
$N^3$ Cubic
$2^n$ Exponential

Running time Calculations - Loops

for(j=0; j < n; ++j){
// 3 Atomics
}

Running time Calculations - Loops with a break

for(j=0; j < n; ++j){
// 3 Atomics
	if(condition) break;
}

Complexity Analysis

Sequential Search

for(size_t i= 0; i < a.size() ;i++){
	if(a[i] == x){return}
}
// θ(n) time complexity

If then for loop

if(condition) i=0;
else
	for(j =0; j < n; j++)
		a[j] = j;
// θ(n) time complexity

Nested Loop Search

for(j =0; j < n; j++){
	// 2 atomics
	for(k =0; k<n; k++){
		// 3 atomics
	}
}
//θ(n^2) time complexity

Consecutive Statementss

for(j = 0; j < n; ++j){
	// 3 atomics
}
for(j = 0; j < n; ++j){
	// 5 atomics
}
// Complexity θ(3n + 5n) = θ(n)