rec2 - Recitation 2 Helping out with homework 1 15-451...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Recitation 2 : Helping out with homework 1 15-451 : Algorithms 1 Asymptotics of polynomials - RLC page 33 Given a positive integer , a polynomial in n of degree is a function ( ) of the form: d i ( )= i d pn pn X i=0 d a :n where d 6= 0. ( ) is asymptotically positive i d 0. if ( ) is asymptotically positive, then ( ) 2 ( d ). a pn a > pn pn n 2 Ranking functions n n log(n) log (n) 2n 2log log n others ... ( ( )) 3 Recursive programs Consider the following piece of recursive C code. Assume the function () takes constant time and returns the oor of the logarithm base 2. What is its worst case asymptotic running time. ilog void P(int n) { if (n == 1) return; P(ilog(n)); } 1 Suppose 2 "" ( ) = ( ( )). k k log n n< (1) = ( ) = ( ( )) + 2 "" ( + 1). Then the running time is + T c0 Tn T log n c1 k c0 k:c1 = 4 Inversions and bubble sort Here is a sort algorithm similar to (but not exactly the same as) bubble sort. void swap(int *a,int i,int j) { int temp = a i]; a i] = a j]; a j] = temp; } void babble_sort(int *a,int n) { for(int i = 0;i < n;i++) { for(j = i+1;j < n;j++) { if(a i] > a j]) swap(a,i,j); } } } Why does this work ? Invariant : after the k-th iteration of the outer loop, there are no inversions involving a 0] ... a k-1]. So the sequence is sorted after the n-th iteration. Finally here is bubble sort: void bubble_sort(int *a,int n) { int i,j; for (j=n-1;j>0;j--) { for (i=0;i<j;i++) { if(a i] > a i+1]) swap(i,i+1); } } } 2 Invariant : After the k-th iteration of the outer loop, there can be no inversions involving a n-k] ... a n-1]. This requires a bit more analysis than the previous case. Fact: After the k-th iteration of the outer loop, a n-k] contains the max of a 0] ... a n-k] at the beginning of the loop. So clearly the invariant holds for k = 1. We show that if it holds upto (k - 1) then it holds upto k. Consider the two ways a n-k] can be involved in an inversion. Case 1. a n-k] is less than some element before it. Not possible because it is the max. Case 2. a n-k] is greater than some element after it. Not possible because then the invariant would have been broken before. So the sequence is sorted after the n-th iteration. 3 ...
View Full Document

Page1 / 3

rec2 - Recitation 2 Helping out with homework 1 15-451...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online