2-4 Inversions
Let be an array of distinct numbers. If and , then the pair is called an inversion of .
a. List the five inversions in the array .
b. What array with elements from the set has the most inversions? How many does it have?
c. What is the relationship between the running time of insertion sort and the number of inversions in the input array? Justify your answer.
d. Give an algorithm that determines the number of inversions in any permutation of elements in worst-case time. ( Modify merge sort).
a. , , , , .
b. The array has the most inversions .
c. The running time of insertion sort is a constant times the number of inversions. Let denote the number of such that . Then equals the number of inversions in .
Now consider the while loop on lines 5-7 of the insertion sort algorithm. The loop will execute once for each element of which has index less than is larger than . Thus, it will execute times. We reach this while loop once for each iteration of the for loop, so the number of constant time steps of insertion sort is which is exactly the inversion number of .
d. We'll call our algorithm for modified merge sort. In addition to sorting , it will also keep track of the number of inversions.
sorts and returns the number of inversions in the elements of , so and track the number of inversions of the form where and are both in the same half of .
returns the number of inversions of the form where is in the first half of the array and is in the second half. Summing these up gives the total number of inversions in . The runtime of the modified algorithm is , which is same as merge sort since we only add an additional constant-time operation to some of the iterations in some of the loops.
COUNT-INVERSIONS(A, p, r)
if p < r
q = floor((p + r) / 2)
left = COUNT-INVERSIONS(A, p, q)
right = COUNT-INVERSIONS(A, q + 1, r)
inversions = MERGE-INVERSIONS(A, p, q, r) + left + right
return inversions
MERGE-INVERSIONS(A, p, q, r)
n1 = q - p + 1
n2 = r - q
let L[1..n1 + 1] and R[1..n2 + 1] be new arrays
for i = 1 to n1
L[i] = A[p + i - 1]
for j = 1 to n2
R[j] = A[q + j]
L[n1 + 1] = ∞
R[n2 + 1] = ∞
i = 1
j = 1
inversions = 0
for k = p to r
if L[i] <= R[j]
A[k] = L[i]
i = i + 1
else
inversions = inversions + n1 - i + 1
A[k] = R[j]
j = j + 1
return inversions