# a1sol - McGill University COMP251 Assignment 1 Solution...

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
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: McGill University COMP251: Assignment 1 Solution Question 1 (a) Idea Let k = ⌈ n 2 ⌉ . Then A [ k ] is the median of A , and B [ k ] is the median of B . The Divide-and-Conquer algorithm arises from the following observation: Observation Suppose that A ( k ) ≥ B ( k ). Then the median of A and B is the same as the median of A [1 . . . k ] and B [( ⌊ n/ 2 ⌋ + 1) . . . n ]. To see why this is true, note that: • Each element in A [( k + 1) . . . n ] is not smaller than 2 k elements B [1 . . . k ] , A [1 . . . k ] • Similarly, each element in B [1 . . . ⌊ n/ 2 ⌋ ] is not larger than 2 k elements B [( ⌊ n/ 2 ⌋ + 1) . . . n ] , A [( k + 1) . . . n ] Consequently, the median of A and B must be among A [1 . . . k ] , B [( ⌊ n/ 2 ⌋ + 1) . . . n ] Moreover, it is the median of the numbers in these two subarrays . Thus, in general we will find the median of the union of A [ x . . . ( x + ℓ − 1)] and B [ y . . . ( y + ℓ − 1)] (i.e. there are the same number of elements from A and B ). The following program Median( x, y, ℓ ) will do this. To solve the given problem, call Median(1 , 1 , n...
View Full Document

{[ snackBarMessage ]}

### Page1 / 2

a1sol - McGill University COMP251 Assignment 1 Solution...

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

View Full Document
Ask a homework question - tutors are online