{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

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

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 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
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

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

View Full Document
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
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

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

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

{[ snackBarMessage ]}

### 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
Ask a homework question - tutors are online