Created
July 2, 2013 17:15
-
-
Save riyadparvez/5911187 to your computer and use it in GitHub Desktop.
Count number of inversions in an array in C#. An inversion in an array is when i<j but a[i]>a[j]. Running time of this algorithm is quadratic O(n*n).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class InversionCounter | |
| { | |
| int[] array; | |
| int inversion = 0; | |
| public InversionCounter (IEnumerable<int> arr) | |
| { | |
| array = arr.ToArray(); | |
| } | |
| private int Merge(int firstStartIndex, int firstEndIndex, | |
| int secondStartIndex, int secondEndIndex) | |
| { | |
| int count = 0; | |
| for (int i = firstStartIndex; i <= firstEndIndex; i++) | |
| { | |
| for (int j = secondStartIndex; j <= secondEndIndex; j++) | |
| { | |
| if(array[i]>array[j]) | |
| { | |
| count++; | |
| } | |
| } | |
| } | |
| return count; | |
| } | |
| private int CountInversion(int start, int end) | |
| { | |
| if(start >= end) | |
| { | |
| return 0; | |
| } | |
| int mid = start + (end-start)/2; | |
| return CountInversion(start, mid) + CountInversion(mid + 1, end) | |
| + Merge(start, mid, mid+1, end); | |
| } | |
| public int GetInversion() | |
| { | |
| return CountInversion(0, array.Length-1); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment