Series Warmup
A really bad way to maintain order• Given a list L in order• Suppose elements get added dynamically• Problem is to keep it in order• Joe has a sort function available Sort(L)• He learned in CS50 not to reinvent any wheels• So when a new element x arrives he appends it to
the end of L: L <- append(L,x) and then calls Sort(L)
• Unbeknownst to Joe, Sort does a bubble sort• How many item comparisons, starting from an
empty list and adding n elements?
Recall Bubble Sort Analysis• ((n-1)∙n)/2 comparisons to sort a list
of length n• So
• But what is the sum of the first n squares?
(i−1)i2i=1
n
∑ =12
i2i=1
n
∑ −12
ii=1
n
∑
• n=4, sum of first 4 squares
• Area = n across and tall
• How big is the white space?
• Let
•
ii=1
n
∑
S(n)= i2i=1
n
∑
I(n)= i =i=1
n
∑ n(n+1)2
Of course this is Θ(n3)!
S(n)= i2i=1
n
∑
I(n)= i =i=1
n
∑ n(n+1)2
S(n)+ I(j)i=1
n
∑ =(n+1)(n)(n +1)
2
S(n)+ i2
2i=1
n
∑ +i2i=1
n
∑ =(n+1)(n)(n +1)
2
32S(n)=n3
2+n2 +
n2
−n2
4−
n4
S(n)=n3
3+
n2
2+
n6
12
i2i=1
n
∑ −12
ii=1
n
∑ =n3
6+
n2
4+
n12
−n2
4−
n4
=n3
6+
3n2
4−
n6
FINIS