Professional Documents
Culture Documents
𝑓 𝑛 = 𝑎+ 𝑏
𝑖=0 𝑗=0
• This is a nested sum because we have a nested loop.
• The inner sum represents the cost of the inner loop.
• It is important that we use different indexes on our sums just like it is important to use different
indexes in our code.
Summation Simplification
𝑛−1 𝑛−𝑖−1
𝑓 𝑛 = 𝑎+ 𝑏
𝑖=0 𝑗=0
𝑛−1 𝑛−1 𝑛−𝑖−1
= 𝑎+ 𝑏
𝑖=0 𝑖=0 𝑗=0
𝑛−1 𝑛−1 𝑛−𝑖−1
=𝑎 1+ 𝑏 1
𝑖=0 𝑖=0 𝑗=0
𝑛−1 𝑛−𝑖−1
= 𝑎𝑛 + 𝑏 1
𝑖=0 𝑗=0
𝑛−1
= 𝑎𝑛 + 𝑏 𝑛−𝑖−1
𝑖=0
𝑛−1
= 𝑎𝑛 + 𝑏 𝑛−𝑖−1
𝑖=0
Summation Simplification
𝑛−1
𝑓 𝑛 = 𝑎𝑛 + 𝑏 𝑛−𝑖−1
𝑖=0
• There are two ways to handle this sum. One straightforward and one clever.
• First the straightforward method.
𝑛−1 𝑛−1 𝑛−1
= 𝑎𝑛 + 𝑏𝑛 1−𝑏 𝑖−𝑏 1
𝑖=0 𝑖=0 𝑖=0
𝑛−1
= 𝑎𝑛 + 𝑏𝑛2 − 𝑏 𝑖 − 𝑏𝑛
𝑖=0
𝑛−1
2
= 𝑎𝑛 + 𝑏𝑛 − 𝑏𝑛 − 𝑏 𝑖
𝑖=0
• We still need to know what this sum results in:
𝑛−1
𝑖
𝑖=0
• This is an arithmetic series. I usually call it Gauss’ Sum.
𝑛−1
𝑛 𝑛−1
𝑖=
2
𝑖=0
Summation Simplification
𝑏𝑛(𝑛 − 1)
𝑓 𝑛 = 𝑎𝑛 + 𝑏𝑛2 − 𝑏𝑛 −
2
2
𝑏𝑛 𝑏𝑛
= 𝑎𝑛 + 𝑏𝑛2 − 𝑏𝑛 − +
2 2
2
𝑏𝑛 𝑏𝑛
= 𝑎𝑛 + −
2 2
Now for the clever method:
𝑛−1
𝑓 𝑛 = 𝑎𝑛 + 𝑏 𝑛−𝑖−1
𝑖=0
𝑛−1
= 𝑎𝑛 + 𝑏 𝑖
𝑖=0
𝑏𝑛 𝑛 − 1
= 𝑎𝑛 +
2
2
𝑏𝑛 𝑏𝑛
= 𝑎𝑛 + −
2 2
Both ways we arrive at the same result. We can conclude our big-oh bound:
𝑓 𝑛 ∈ 𝑂 𝑛2
Insertion Sort
private static void insertionSort(List<Integer> list) {
// insert the ith item into items 0 to i-1 in the proper position
for(int i = 1; i < list.size(); i++){
for(int j = i; j > 0 && list.get(j) < list.get(j-1); j--) {
swap(list, j, j-1);
}
}
}
𝑓(𝑛) = 𝑎+ 𝑏
𝑖=1 𝑗=1
• Can we simplify the summation now that we have it?
Summation Simplification
𝑛−1 𝑖
𝑓(𝑛) = 𝑎+ 𝑏
𝑖=1 𝑗=1
𝑛−1
=𝑎 𝑛−1 +𝑏 𝑖
𝑖=1
𝑏𝑛 𝑛 − 1
=𝑎 𝑛−1 +
2
2
𝑏𝑛 𝑏
= + 𝑎− 𝑛−𝑎
2 2
𝑓(𝑛) ∈ 𝑂 𝑛2
𝑓(𝑛) = 𝑎+ 𝑏
𝑖=0 𝑗=𝑖+1
• Can we simplify the summation now that we have it?
Summation Simplification
𝑛−1 𝑛−1
𝑓(𝑛) = 𝑎+ 𝑏
𝑖=0 𝑗=𝑖+1
𝑛−1 𝑛−1
= 𝑎𝑛 + 𝑏 1
𝑖=1 𝑗=𝑖+1
𝑛−1
= 𝑎𝑛 + 𝑏 𝑛−1 − 𝑖+1 +1
𝑖=1
𝑛−1
= 𝑎𝑛 + 𝑏 𝑛−𝑖−1
𝑖=1
𝑏𝑛2 𝑏𝑛
= 𝑎𝑛 + −
2 2
𝑓(𝑛) ∈ 𝑂 𝑛2