public InversionCount MergeInversion(int[] left, int[] right) { InversionCount icTemp = new InversionCount(); List <int> SortedList = new List <int>(); var leftList = left.ToList <int>(); var rightList = right.ToList <int>(); while (leftList.Count > 0 || rightList.Count > 0) { if (leftList.Count > 0 && rightList.Count > 0) { if (leftList.First <int>() > rightList.First <int>()) { SortedList.Add(rightList.First <int>()); rightList.Remove(rightList.First <int>()); foreach (var item in leftList) { icTemp.inversionCount++; } } else { SortedList.Add(leftList.First <int>()); leftList.Remove(leftList.First <int>()); } } else if (leftList.Count == 0) { SortedList.Add(rightList.First <int>()); rightList.Remove(rightList.First <int>()); } else if (rightList.Count == 0) { SortedList.Add(leftList.First <int>()); rightList.Remove(leftList.First <int>()); } } icTemp.sortedArray = SortedList.ToArray(); return(icTemp); }
public InversionCount SortCount(int[] a) { InversionCount ic = new InversionCount(); List <int> firsthalf = new List <int>(); List <int> secondhalf = new List <int>(); int middle = a.Length / 2; if (a.Length == 1) { return(ic = new InversionCount { sortedArray = a, inversionCount = 0 }); } else { for (int i = 0; i < middle; i++) { firsthalf.Add(a[i]); } for (int j = middle; j < a.Length; j++) { secondhalf.Add(a[j]); } var ic1 = SortCount(firsthalf.ToArray()); ic.inversionCount += ic1.inversionCount; var ic2 = SortCount(secondhalf.ToArray()); ic.inversionCount += ic2.inversionCount; var ic3 = MergeInversion(ic1.sortedArray, ic2.sortedArray); ic3.inversionCount += ic.inversionCount; return(ic3); } }