# HW3_sol_SP2022.pdf - Homework #3 Solutions CS 344: Design...

• 7

Course Hero uses AI to attempt to automatically extract content from documents to surface to you and others so you can study better, e.g., in search results, to enrich docs, and more. This preview shows page 1 - 2 out of 7 pages.

Homework #3 SolutionsCS 344: Design and Analysis of Computer Algorithms (Spring 2022)Problem 1Say there areqarraysA1, A2, ..., Aq. Each arrayAiis sorted from smallest to largest. Youcan assume all numbers are distinct: so if a numberxappears in someAi, thenxappearsinAiexactly once and alsoxdoes not appear in any of the otherAj. Defineni=len(Ai)and defineN=qi=1ni. That is,Nis the total number of elements among all the arrays.Write pseudocode that outputs asortedarrayB[0....N1]of lengthNsuch thatBcontains all the elements from all theAi. That is, ifxis someAjthenxshould appear inB. Note thatBshould be sorted from smallest to largest.Your algorithm should run in timeO(Nlog(q)).You will want to use the heap datastructure. You must make it clear why the run-time isO(Nlog(q))by analyzing how oftenyou call each heap operation.At a high level, our algorithm maintainsqpointers, one for each arrayAi. In eachstep, the algorithm adds to the output the smallest element pointed to, and thenincrements the corresponding pointer or ceases to maintain the corresponding pointerif increasing it brings it out of bounds. Once all pointers are no longer maintained(that is,Nelements have been accumulated), the algorithms returns.To obtain an efficient implementation, we maintain the elements pointed to in apriority queue.In this way, extracting the minimum element in the priority queuegives us the next smallest value to add to the output. We then need to increment thecorresponding pointer and update the priority queue. To do this, we also associatewith each item in the priority queue the details of a pointer.Merge(A1[0..n11], . . . , Aq[0..nq1]):NniHBuildMinHeap()fori1toqH.add(Ai[0],(i,0))initializeB[0..N1]forj0toN1B[j],(i, k)H.find-min()H.delete-min()ifk+ 1< niH.add(Ai[k+ 1],(i, k+ 1))returnBCorrectness.Correctness can be established by observing the following loop in-variant is maintained by the second loop: in the beginning of iterationj,Hcontainsthe smallest element ofA1∪ · · · ∪Aqthat is not already present inB. Indeed, if thisinvariant holds, then clearlyBwill contain the elements in sorted order after the loop.This can be formally proven by induction.

Upload your study docs or become a

Course Hero member to access this document

Upload your study docs or become a

Course Hero member to access this document

End of preview. Want to read all 7 pages?

Upload your study docs or become a

Course Hero member to access this document

Term
Spring
Professor
Hari
Tags
Big O notation, Selection algorithm