HW4_sol - Solutions to Homework 4 Section 3.1 30(a The...

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

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

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Solutions to Homework 4 Section 3.1 30. (a) The following algorithm will find all modes in the sequence and put them into a list L. At each point in the execution of this algorithm, modecount is the number of occurrences of the elements found to occur most often so far ( the elements in L). Whenever a more frequently occurring element is found (the main inner loop), modecount and L are updated, whenever an element is found with this same count, it is added to L. procedure: find all modes(a_1,a_2,...,a_n: nondecreasing integers) modecount:=0 i:=1 while i<=n begin value:=a_i count:=1 while i<=n and a_i=value begin count:=count+1 i:=i+1 end if count>modecount then begin modecount:=count set L to consist just of value end else if count=modecount then add value to L end {L is a list of all the value occurring most often} (b) 8n (c)2n+1 1 (d) The algorithm we gave for finding all the modes essentially just goes through the list once. I particular, between any two successive executions of the statement i:=i+1 there are at most about eight operations. Therefore at most about 8n steps are done in all, so the time complexity in all cases is O ( n ) . 34. Step1: 2,3,1,5,4,6 Step2: 2,1,3,4,5,6 Step3: 1,2,3,4,5,6 Step4: 1,2,3,4,5,6 Step5: 1,2,3,4,5,6 38. Step1: 2,6,3,1,5,4 Step2: 2,3,6,1,5,4 Step3: 1,2,3,6,5,4 Step4: 1,2,3,5,6,4 Step5: 1,2,3,4,5,6 Custom 1 Step1: 1,6,2,3,5,4 Step2: 1,2,6,3,5,4 Step3: 1,2,3,6,5,4 Step4: 1,2,3,4,6,5 Step5: 1,2,3,4,5,6 44. (a) We carry out the binary search algorithm given as Algorithm 3 in this section, except that we replace the final check with if x<a_i then location:=i else location:=i+1 (b) For Algorithm 3, the best-case and worst-case comparison numbers are the same d log 2 n e , which is O (log 2 n ) ....
View Full Document

{[ snackBarMessage ]}

Page1 / 6

HW4_sol - Solutions to Homework 4 Section 3.1 30(a The...

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

View Full Document
Ask a homework question - tutors are online