Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views1 page

Inversion

The document presents an algorithm for counting inversions in an array using a modified merge sort approach. It includes two main algorithms: Merge-Sort-Count-Inversion, which recursively divides the array and counts inversions, and Merge-Count-Inversion, which merges two sub-arrays while counting cross inversions. The algorithms efficiently combine sorting and inversion counting in a single process.

Uploaded by

Lil Baby
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views1 page

Inversion

The document presents an algorithm for counting inversions in an array using a modified merge sort approach. It includes two main algorithms: Merge-Sort-Count-Inversion, which recursively divides the array and counts inversions, and Merge-Count-Inversion, which merges two sub-arrays while counting cross inversions. The algorithms efficiently combine sorting and inversion counting in a single process.

Uploaded by

Lil Baby
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

1 Counting Inversion Problem

Algorithm 1 Merge-Sort-Count-Inversion(A, low, high)


1: countInv ← 0
2: if low < high then
3: mid = low + (high−low)/2
4: countInv ← countInv + Merge-Sort-Count-Inversion(A, low, mid)
5: countInv ← countInv + Merge-Sort-Count-Inversion(A, mid + 1, high)
6: countInv ← countInv + Merge-Count-Inversion(A, low, high, mid)
7: end if
8: return countInv

Algorithm 2 Merge-Count-Inversion(A, low, high, mid)


. For first sub-array the index is from low . . . mid
. For second sub-array the index is from mid + 1 . . . high
1: n1 ← mid − low + 1 . Number of elements in the first sub-array
2: n2 ← high − mid . Number of elements in the second sub-array
3: left[1 . . . n1 + 1] . Create a sub-array of size n1 + 1
4: right[1 . . . n2 + 1] . Create a sub-array of size n2 + 1
5: for i ← 1 to n1 do
6: left[i] ← A[low + i − 1]
7: end for
8: for j ← 1 to n2 do
9: right[j] ← A[mid + j]
10: end for
11: left[n1 + 1] ← ∞
12: right[n2 + 1] ← ∞
13: i ← 1
14: j ← 1
15: start ← low
16: crossInv ← 0
17: while (i ≤ n1 k j ≤ n2 ) do
18: if (left[i] ≤ right[j]) then
19: A[start] ← left[i]
20: start ← start + 1
21: i←i+1
22: else . Inversion case
23: A[start] ← right[j]
24: start ← start + 1
25: j ←j+1
26: crossInv ← crossInv + (mid − i + 1) . Inversion because of right[j]
27: end if
28: end while
29: return crossInv

You might also like