APS1070 Lecture (2) Slides
APS1070 Lecture (2) Slides
Samin Aref
▶ A sequence is a function f : N → R.
Sums
▶ A sequence is a function f : N → R.
▶ Notation: f0 , f1 , f2 , · · · where fi = f (i).
Sums
▶ A sequence is a function f : N → R.
▶ Notation: f0 , f1 , f2 , · · · where fi = f (i).
▶ Sum: fm + fm+1 + · · · + fn = ni=m fi .
P
Sums
▶ A sequence is a function f : N → R.
▶ Notation: f0 , f1 , f2 , · · · where fi = f (i).
▶ Sum: fm + fm+1 + · · · + fn = ni=m fi .
P
▶ Important sums:
n
X n(n + 1)
i=
2
i=1
n
X a n+1 − am
ai = .
a−1
i=m
Part 1
▶ Running time?
Algorithm 3 Swapping two elements in an array
Require: 0 ≤ i ≤ j ≤ n − 1
function swap(array a[0..n − 1], integer i, integer j)
t ← a[i]
a[i] ← a[j]
a[j] ← t
return a
▶ Running time?
▶ This is a constant time algorithm.
Algorithm 5 Finding the maximum in an array
function findmax(array a[0..n − 1])
k←0 ▷ location of maximum so far
for j ← 1 to n − 1 do
if a[k] < a[j] then
k=j
return k
▶ Running time?
Algorithm 5 Finding the maximum in an array
function findmax(array a[0..n − 1])
k←0 ▷ location of maximum so far
for j ← 1 to n − 1 do
if a[k] < a[j] then
k=j
return k
▶ Running time?
▶ This is a linear time algorithm, since it makes one pass
through the array and does a constant amount of work each
time.
Snippet: other loop increments
▶ Running time?
Snippet: other loop increments
▶ Running time?
▶ This runs in logarithmic time because i doubles about lg n
times until reaching n.
Example: nested loops
▶ Running time?
Example: nested loops
▶ Running time?
▶ The first iteration of the outer loop takes n elementary
operations. The second iteration of the outer loop takes n − 1
operations and so forth. Therefore, the algorithm takes
n + (n − 1) + · · · + 1 = n(n + 1)/2 elementary operations for
input size n.
Warm call
mm−1 m−n+1 m!
Q(m, n) = ... = .
m m m (m − n)!mn
Analysis of balls in bins
mm−1 m−n+1 m!
Q(m, n) = ... = .
m m m (m − n)!mn
▶ Q(m, n) = 0 unless 0 ≤ n ≤ m.
Plots of Q(m, n) against n, m = 25, 100, 400, 1600
Plots of Q(m, n) against n, m = 25, 100, 400, 1600