01 - Introduction and Analysis
01 - Introduction and Analysis
g(n) = n2
g(n) = lg n
g(n) = n
g(n) = n3
❑ An potentially unbounded
bank of memory cells, 2
1
each of which can hold an 0
arbitrary number or
character
Memory cells are numbered and accessing
any cell in memory takes unit time.
© 2010 Goodrich, Tamassia Analysis of Algorithms 15
Primitive Operations
❑ Basic computations
❑ Examples:
performed by an algorithm
◼ Evaluating an
❑ Identifiable in pseudocode expression
❑ Largely independent from the ◼ Assigning a value
to a variable
programming language
◼ Indexing into an
❑ Exact definition not important array
(we will see why later) ◼ Calling a method
Returning from a
❑ Assumed to take a constant ◼
method
amount of time in the RAM
model
1
1 10 100 1,000
n
◼ 3n3 + 20n2 + 5
3n3 + 20n2 + 5 is O(n3)
need c > 0 and n0 1 such that 3n3 + 20n2 + 5 c•n3 for n n0
this is true for c = 4 and n0 = 21
◼ 3 log n + 5
3 log n + 5 is O(log n)
need c > 0 and n0 1 such that 3 log n + 5 c•log n for n n0
this is true for c = 8 and n0 = 2
© 2010 Goodrich, Tamassia Analysis of Algorithms 24
Big-Oh Rules
big-Theta
◼ f(n) is (g(n)) if there are constants c’ > 0 and c’’
> 0 and an integer constant n0 1 such that
c’•g(n) f(n) c’’•g(n) for n n0
quicksort(A, i, j) {
pivot = A[i];
for(k = i+1 to j) {
if(pivot > A[k]) {
…
}
Start with these Then do this
else { Then this …
…
}
…
}
foo(A, n) {
…
k = (j+91)/3; O(1)
m = max(A, n); O(n) (finding maximum of an array takes linear time)
p = (j – 17) + max(B, n) O(1) + O(n) = O(n)
…
}
foo(A, n) {
…
if( p < A[i] ) { O(1)
… O(n)
} The whole if statement
else { takes time
O(1) + max(O(n), O(n2))
… O(n2)
= O(n2)
}
}
© 2019 Shermer Analysis of Algorithms 35
Loops
◼ Add up the time in the body of the loop.
◼ Determine how many times t the loop will be executed,
as a function of your n. Use worst-case estimate.
◼ The time for the loop is t * (time for body)
i = 0;
while(p < A[i]) { n iterations
…
i++;
}
© 2019 Shermer Analysis of Algorithms 36
Triangular Loops
◼ Triangular loops have an inner index that counts up to
the outer index.
◼ Assume the inner loops have the same number of
iterations as the outer loop.
for(i = 1 to n ) { n iterations
…
for(j = 1 to i) { n iterations
…
}
}