(Latest Revision:
Apr 26, 2020)
Sort and Count Problem Solution
EXAMPLE:
The solution is worked out according to the Sort-and-Count algorithm explained in section 5.3 of our text: "Counting Inversions"
The initial list is:26 81 87 32 66 72 86 97 23 48 14 71 89 18 49 62
Sort-and-Count makes two recursive calls.
The first recursive call inputs the first half of the initial
list: 26 81 87 32 66 72 86 97
and returns the sorted version of the first half, as well as the number of inversions found in the first half (7).
The second recursive call inputs the second half of the initial
list: 23 48 14 71 89 18 49 62
and returns the sorted version of the second half, as well as the number of inversions found in the second half (10).
Sort-and-Count then calls Merge-and-Count. To Merge-and-Count, Sort-and-Count
passes the sorted versions of the two halves of the original
list:26 32 66 72 81 86 87 97, and
14 18 23 48 49 62 71 89
Merge-and-Count begins merging the two half-lists together, while counting
inversions.26 32 66 72 81 86 87 97 14 18 23 48 49 62 71 89
14 18 23 26 32 48 49 62 66 71 72 81 86 87 89 97
8 8 8 6 6 6 5 1 (inversions)
The inversions counted during the merge are shown in the last line above. The total number of inversions counted between the two sorted halves is
8+8+8+6+6+6+5+1 = 48.
Therefore the total number of inversions in the original list is
7+10+48 = 65.