Series Warmup

6
Series Warmup

description

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 - PowerPoint PPT Presentation

Transcript of Series Warmup

Page 1: Series  Warmup

Series Warmup

Page 2: 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?

Page 3: Series  Warmup

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

Page 4: Series  Warmup

• 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

Page 5: Series  Warmup

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

Page 6: Series  Warmup

FINIS