05 - Algorithms Divide and Conquer Divide and Conquer II...

Info iconThis preview shows pages 1–7. Sign up to view the full content.

View Full Document Right Arrow Icon
Algorithms – Divide and Conquer Divide and Conquer II Design and Analysis of Algorithms Andrei Bulatov
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Algorithms – Divide and Conquer 5-2 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
Background image of page 2
Algorithms – Divide and Conquer 5-3 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
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Algorithms – Divide and Conquer 5-4 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
Background image of page 4
Algorithms – Divide and Conquer 5-5 Algorithm Merge-and-Count(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+(last1-curr1+1) endif endwhile output the rest of the non-empty half and count
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Algorithms – Divide and Conquer 5-6 Algorithm (cntd) Sort-and-Count(L) If last=1 then no inversions else do divide L into two halves: A contains the first
Background image of page 6
Image of page 7
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.

Page1 / 21

05 - Algorithms Divide and Conquer Divide and Conquer II...

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online