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 SortL • He learn
Trang 1Series Warmup
Trang 2A 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?
Trang 3Recall 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) ι
2
ι =1
ν
2 ι2
ι =1
ν
ι =1
ν
∑
Trang 4• n=4, sum of first 4
squares
• Area = n across and tall
• How big is the white space?
• Let
•
i
i=1
ν
∑
S(n) = ι2
ι=1
ν
∑
Ι ( ν ) = ι =
ι=1 ν
∑ ν ( ν 2 +1)
Trang 5Of course this is Θ(n3)!
S(n) = ι2
ι=1
ν
∑
Ι ( ν ) = ι =
ι=1
ν
∑ ν ( ν 2 +1)
S(n) + Ι ( ϕ )
ι=1
ν
∑ = ( ν +1)( ν )( ν +1)
2
Σ ( ν ) + ι2
2
ι=1
ν
∑ + ι
2
ι=1
ν
∑ = ( ν +1)( ν )( ν +1)
2 3
2 Σ ( ν ) = ν3
2 + ν2 + ν
2 −
ν2
4 −
ν
4
Σ ( ν ) = ν3
3 +
ν2
2 +
ν
6
1
2
i=1
ν
ι=1
ν
ν2
ν
ν2
ν
4
ν2
ν
6
Trang 6FINIS