This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: Recitation 2 : Helping out with homework 1 15451 : 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 kth iteration of the outer loop, there are no inversions involving a 0] ... a k1]. So the sequence is sorted after the nth iteration. Finally here is bubble sort:
void bubble_sort(int *a,int n) { int i,j; for (j=n1;j>0;j) { for (i=0;i<j;i++) { if(a i] > a i+1]) swap(i,i+1); } } } 2 Invariant : After the kth iteration of the outer loop, there can be no inversions involving a nk] ... a n1]. This requires a bit more analysis than the previous case. Fact: After the kth iteration of the outer loop, a nk] contains the max of a 0] ... a nk] 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 nk] can be involved in an inversion. Case 1. a nk] is less than some element before it. Not possible because it is the max. Case 2. a nk] 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 nth iteration. 3 ...
View
Full
Document
 Spring '09
 Naver
 Algorithms

Click to edit the document details