95%(19)18 out of 19 people found this document helpful
This preview shows page 8 - 9 out of 9 pages.
c) Let’s develop a runtime recursion for an algorithm that computesfi(3by3blocks7. (1 level)Optional bonus problem: More medians(This is anoptionalchallenge problem. It is not the most effective way to raise your grade in the course.Only solve it if you want an extra challenge.)We saw in class a randomized algorithm for computing the median, where the expected running time wasO(n). Design a algorithm for computing the median where theworst-caserunning time isO(n).Hint: It’s all in finding a good pivot.Pseudocode:CS 170, Fall 2016, HW 28
1:functionSELECT(k,A)2:n←size ofA3:ifn≤100then4:L←sorted version ofA5:returnL[n/2]6:M←empty list of sizen/57:fori=0,1,...,n/5-1do8:M[i]←median ofA[5i,5i+4]9:m←Select(n/10,M)10:Alow←elements ofAless thanm11:Ahigh←elements ofAgreater thanm12:r←rank ofminA(compute in linear time)13:ifk≤rthen14:returnSelect(k,Alow)15:else16:returnSelect(k-r,Ahigh)Running time analysis:The algorithm does linear work to recur on a list of sizen/5 and 3n/4. This yields a recursion ofT(n)≤T(3n/4)+T(n/5)+nWriting out the recursion tree yields a bound ofT(n)≤n+(3/4+1/5)n+(3/4+1/5)2n+...=O(n)as desired.