Transcript warmup
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 n (i 1)i 1 n 2 1 n • So i i i1 2 2 i1 2 i1 • But what is the sum of the first n squares? • n=4, sum of first 4 squares • Area = n across and i tall n i1 • How big is the white space? • Let n S(n) i 2 • i1 n(n 1) I (n) i 2 i1 n n S(n) i 2 i1 n(n 1) I (n) i 2 i1 n n S(n) I( j) i1 (n 1)(n)(n 1) 2 i 2 n i (n 1)(n)(n 1) S(n) 2 i1 2 i1 2 n 3 n3 n n2 n 2 S(n) n 2 2 2 4 4 n3 n2 n S(n) 3 2 6 1 n 2 1 n n 3 n2 n n2 n i 2 i 6 4 12 4 4 2 i1 i1 n 3 3n 2 n 6 4 6 Of course this is Θ(n3)! FINIS