This preview shows pages 1–2. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: CS 473: Algorithms, Fall 2010 HW 4 (due Tuesday, September 28th) This homework contains four problems. Read the instructions for submitting homework on the course webpage . In particular, make sure that you write the solutions for the problems on separate sheets of paper; the sheets for each problem should be stapled together. Write your name and netid on each sheet. Collaboration Policy: For this home work, Problems 13 can be worked in groups of up to 3 students each. Problem 0 should be answered in Compass as part of the assessment HW4Online and should be done individually. 1. (30 pts) You are given an array A of n distinct integers, and an integer k such that 1 k n . The square distance between a pair of integers x,y is defined as the quantity ( x y ) 2 . Your goal is to design an O ( n ) time algorithm to find k elements in A with the smallest square distance to the median (i.e. the element of rank b n/ 2 c in A ). For instance, if A = [9 , 5 , 3 , 1 , 2] and k = 2, then the median element is 1, and the 2 elements in A with the smallest square distance to the median are { 1 , 2 } . If k = 3, then you can output either { 1 , 2 , 3 } or { 1 , 2 , 5 } . Hint: Use the linear time Selection algorithm. Solution : In the lecture notes we are given an O ( n ) time algorithm SELECT ( A,j ), which finds the j th smallest element in the array A . So by calling SELECT ( A, b n/ 2 c ) we get the median of A , call it m . We then can create an array B [1 ...n ], where B [ i ] = ( A [ i ] m ) 2 . Filling in B can be done by making a single pass through A , doing O (1) work at each step, and hence takes O ( n ) time. We now wish to find the smallest k elements in B , since these are the elements with the smallest squared distance to the median. We now call SELECT ( B,k ), to find the k th smallest element in B . We can then do a linear time pivot operation to determine the indices of all the values less than the k th smallest element in B (i.e. one round of Quicksort, where we store the indices instead of the values). We can then retrieve the corresponding elements from A since the indices in B match the indices of the corresponding values from A ....
View
Full
Document
 Spring '08
 Chekuri,C
 Algorithms

Click to edit the document details