Skip to content

Instantly share code, notes, and snippets.

@delphic
Last active December 19, 2015 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save delphic/5960293 to your computer and use it in GitHub Desktop.
Save delphic/5960293 to your computer and use it in GitHub Desktop.
Console Program to calculate inversions in an array.
using System;
using System.IO;
using System.Linq;
namespace CountingInversions
{
class MainClass
{
public static void Main (string[] args)
{
var input = InputGetter.GetInput(@"C:\InputFile.txt");
int[] sortedArray;
Console.WriteLine("Please wait counting inversions...");
var result = CountAndSort(input, out sortedArray);
Console.WriteLine(result);
}
static Int64 CountAndSort(int[] input, out int[] output)
{
Int64 count = 0;
if(input.Length == 1)
{
output = input;
return count;
}
int[] left, right;
int leftLength = input.Length/2;
count += CountAndSort(input.Take(leftLength).ToArray(), out left);
count += CountAndSort(input.Skip(leftLength).ToArray(), out right);
count += CountSplitAndMerge(left, right, out output);
return count;
}
static Int64 CountSplitAndMerge(int[] left, int[] right, out int[] output)
{
Int64 count = 0;
int i = 0, j = 0, l = left.Length + right.Length;
output = new int[l];
for(int k = 0; k < l; k++)
{
if(i < left.Length && (j >= right.Length || left[i] < right[j]))
{
output[k] = left[i];
i++;
}
else
{
output[k] = right[j];
j++;
count+=(left.Length-i);
}
}
return count;
}
}
static class InputGetter
{
public static int[] GetInput(string path)
{
var input = File.ReadAllLines(path);
var result = new int[input.Length];
for(int i = 0, l = input.Length; i < l; i++)
{
result[i] = int.Parse(input[i]);
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment