HW5 SOLUTION
1.
chapter 5
Problem 1:
Since we can find the
k

th
value in each database by spec
ify a value
k
, we consider the two databases as two sorted arrays(Querying the
database by specifying k is equivalent to get the
k

th
value in the sorted ar
ray) and our problem is equivalent to find the median value in two sorted ar
rays. We denote
A
[1
, n
]
, B
[1
, n
] as the sorted array in increasing order and
A
[
k
] as
the
k

th
element in the array. For brevity of our computation we assume that
n
= 2
s
.
First we compare
A
[
n/
2] to
B
[
n/
2].
Without loss of generality, assume
that
A
[
n/
2]
< B
[
n/
2], then the elements
A
[1]
, ..., A
[
n/
2] are smaller than n ele
ments, that is,
A
[
n/
2]
, ..., A
[
n
] and
B
[
n/
2]
, ..., B
[
n
]. Thus
A
[1]
, ..., A
[
n/
2] can’t be
the median of the two databases. Similarly,
B
[
n/
2]
, ..., B
[
n
] can’t be the median of
the two databases either. Note that
m
is the median value of
A
and
B
if and only if
m
is the median of
A
[
n/
2]
, ..., A
[
n
] and
B
[1]
, ..., B
[
n/
2](We delete the same number
of numbers that are bigger than
m
and smaller than
m
), that is, the
n/
2 smallest
number of
A
[
n/
2]
, ..., A
[
n
] and
B
[1]
, ..., B
[
n/
2]. Hence the resulting algorithm is:
Algorithm 1 Medianvalue(
A
[1
, n
]
, B
[1
, n
]
, n
)
if
n
= 1 then
return min(A[n],B[n]);
else if
A
[
n/
2]
> B
[
n/
2]
Medianvalue(
A
[1
, n/
2]
, B
[
n/
2
, n
]
, n/
2)
else if
A
[
n/
2]
< B
[
n/
2]
Medianvalue(
A
[
n/
2
, n
]
, B
[1
, n/
2]
, n/
2)
end if
For running time, assume that the time for the comparison of two numbers is
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.
 Summer '06
 Shamsian
 Algorithms, Databases, Recursion, Sort, Invocation

Click to edit the document details