Midterm I, Part 2 – Version B
Oct. 10, 2011
2:00pm  2:50pm
CS431
CS531
(Please circle one)
First Name (Print):
Last Name (Print):
UB ID number:
1. This is a closed book, closed notes exam.
2. You must support your answer.
3. Write your name on the top righthand corner of every page.
4. There are 5 problems and 18 points. in this exam.
0
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Name
6.(8 points) Let
A
[1
,
· · ·
,n
] be an unsorted array. All elements in A are distinct. A reversal of A
is a pair of indices i,j such that
i < j
and
A
[
i
]
> A
[
j
]. The problem is to calculate the number
of reversals in
A
[1
,
· · ·
,n
]. For example consider the following array:
A
=
{
4
,
3
,
1
,
5
,
0
}
.
The reversals in A are: (4
,
3),(4
,
1),(4
,
0), (3
,
1), (3
,
0), (1
,
0), (5
,
0). The number of the
reversals in A is thus 7, which is the answer for this particular array.
Describe a DaC algorithms for calculating the number of reversals in
A
[1
,
· · ·
,n
]. You may
assume
n
is a power of 2. The runtime of the algorithm must be
O
(
n
log
n
) (or less).
Hint: Modify the Merge Sort algorithms.
Answer:
We modify the MergeSort algorithm (which we call FindPair) as follows.
In
addition to sort the input array, it also returns the number of reversals in
S
:
Pseudocode
:
FindPair
(
S
[
p,r
])
1
if
r
==
p
2
This is the end of the preview.
Sign up
to
access the rest of the document.
 Fall '11
 XINHE
 Algorithms, Master Theorem, Time Analysis, unsorted array

Click to edit the document details