Last active
December 19, 2015 13:09
-
-
Save delphic/5960293 to your computer and use it in GitHub Desktop.
Console Program to calculate inversions in an array.
This file contains 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
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