Skip to content
Related Articles

Related Articles

Improve Article

C# Program for Count Inversions in an array | Set 1 (Using Merge Sort)

  • Last Updated : 11 Dec, 2018

Inversion Count for an array indicates – how far (or close) the array is from being sorted. If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is the maximum.
Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.

Example:
The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3).

Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

C#




// C# program to count inversions
// in an array
using System;
using System.Collections.Generic;
  
class GFG {
  
    static int[] arr = new int[] { 1, 20, 6, 4, 5 };
  
    static int getInvCount(int n)
    {
        int inv_count = 0;
  
        for (int i = 0; i < n - 1; i++)
            for (int j = i + 1; j < n; j++)
                if (arr[i] > arr[j])
                    inv_count++;
  
        return inv_count;
    }
  
    // Driver code
    public static void Main()
    {
        Console.WriteLine("Number of "
                          + "inversions are "
                          + getInvCount(arr.Length));
    }
}
  
// This code is contributed by Sam007
Output:
Number of inversions are 5

METHOD 2(Enhance Merge Sort): Suppose we know the number of inversions in the left half and right half of the array (let be inv1 and inv2), what kinds of inversions are not accounted for in Inv1 + Inv2? The answer is – the inversions we have to count during the merge step. Therefore, to get number of inversions, we need to add number of inversions in left subarray, right subarray and merge().


Please refer complete article on Count Inversions in an array | Set 1 (Using Merge Sort) for more details!

My Personal Notes arrow_drop_up
Recommended Articles
Page :