CountingInversion Full
CountingInversion Full
Counting Inversions
• Sites tries to match your item (e.g. books) preferences with others.
– You rank n items.
– The site consults database to find people with similar tastes.
– Based on how you and they rate various things – it can recommend new things these other
people have liked.
• Divide-and-conquer.
1 5 4 8 10 2 6 9 12 11 3 7
Counting Inversions: Divide-and-Conquer
• Divide-and-conquer.
– Divide: separate list into two pieces.
1 5 4 8 10 2 6 9 12 11 3 7
Divide: O(1).
1 5 4 8 10 2 6 9 12 11 3 7
Counting Inversions: Divide-and-Conquer
• Divide-and-conquer.
– Divide: separate list into two pieces.
– Conquer: recursively count inversions in each half.
1 5 4 8 10 2 6 9 12 11 3 7
1 5 4 8 10 2 6 9 12 11 3 7
Conquer: 2T(n / 2)
Counting Inversions: Divide-and-Conquer
• Divide-and-conquer.
– Divide: separate list into two pieces.
– Conquer: recursively count inversions in each half.
– Combine: count inversions where ai and aj are in different halves, and
return sum of three quantities
1 5 4 8 10 2 6 9 12 11 3 7
1 5 4 8 10 2 6 9 12 11 3 7