Solution: Inversion Count in an Array
Learn to calculate the inversion count using the divide and conquer paradigm.
We'll cover the following...
Solution 1
The naive solution to this problem involves the following:
- We pick an element from the array.
- We compare it with all elements to its right.
- If the element on the right is smaller, we increment the inversion count.
using System;public class Program{/// <summary>/// Finds the inversion count in the array./// </summary>/// <param name="arr">Array of integers.</param>/// <returns>The inversion count of the array.</returns>public static int InversionCount(int[] arr){int size = arr.Length;int invCount = 0; // variable to store inversion countfor (int curr = 0; curr < size - 1; curr++){for (int right = curr + 1; right < size; right++){if (arr[curr] > arr[right]){invCount++;}}}return invCount;}// Driver code to test the above methodpublic static void Main(string[] args){int[] arr = { 3, 8, 2, 7, 5, 6 };int result = InversionCount(arr);Console.WriteLine("Number of inversions are " + result);}}
Time complexity
The array is traversed once for each element in it. It runs in ...