This preview shows pages 1–7. Sign up to view the full content.
Algorithms – Divide and Conquer
Divide and Conquer II
Design and Analysis of Algorithms
Andrei Bulatov
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document Algorithms – Divide and Conquer
52
Counting Inversions
Comparing two rankings
A ranking is a permutation of some objects
Objects can be numbered, and one of the rankings is just the natural
order
The Counting Inversions Problem
Instance
:
A permutation
of numbers
1, …, n
Objective
:
Find the number of pairs
i,j ,
i < j
such that
n
a
a
,
,
1
K
j
i
a
a
Algorithms – Divide and Conquer
53
Algorithm Idea
Straightforward algorithm
takes
O(
)
time
Use divide and conquer approach:
split the sequence into two halves
find the number of inversions in the halves
2
n
then what?
Observation
:
`Between halves’
inversion
have the form
where
is in
the first half,
is in the second half,
and
j
i
a
a
)
,
(
j
i
a
a
i
a
j
a
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document Algorithms – Divide and Conquer
54
Algorithm Idea
(cntd)
Assuming that the two halves are sorted we can run a procedure similar
to
Merge
If this card is greater that
the one on the top of the
second half, then all cards
in the rest of the first half
first half
second half
form an inversion
Algorithms – Divide and Conquer
55
Algorithm
MergeandCount(A,B)
set curr1:=1, curr2:=1
/* current cards in halves
set count:=0
/* # of inversions
while curr1
≠
last1+1 and curr2
≠
last2+1
if A[curr1]
≤
B[curr2] then do
output A[curr1]
set curr1:=curr1+1
else do
output A[curr2]
set curr2:=curr2+1
set count:=count+(last1curr1+1)
endif
endwhile
output the rest of the nonempty half and count
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document Algorithms – Divide and Conquer
56
Algorithm (cntd)
SortandCount(L)
If last=1 then no inversions
else do
divide L into two halves:
A contains the first
This is the end of the preview. Sign up
to
access the rest of the document.
This note was uploaded on 11/11/2009 for the course CS 405/705 taught by Professor Bulatov during the Fall '09 term at Simon Fraser.
 Fall '09
 Bulatov
 Algorithms

Click to edit the document details