private static MaxSubarrayResult SolveRecursive(int[] data, int lowIndex, int highIndex) { if (lowIndex == highIndex) { return new MaxSubarrayResult { MaxSum = data[lowIndex], StartIndex = lowIndex, EndIndex = lowIndex } } ; int midIndex = (lowIndex + highIndex) / 2; MaxSubarrayResult leftResult = SolveRecursive(data, lowIndex, midIndex); MaxSubarrayResult rightResult = SolveRecursive(data, midIndex + 1, highIndex); MaxSubarrayResult midResult = SolveMid(data, lowIndex, midIndex, highIndex); if (leftResult.MaxSum >= rightResult.MaxSum && leftResult.MaxSum >= midResult.MaxSum) { return(leftResult); } else if (rightResult.MaxSum >= leftResult.MaxSum && rightResult.MaxSum >= midResult.MaxSum) { return(rightResult); } else { return(midResult); } }
public override bool Equals(object other) { MaxSubarrayResult otherResult = other as MaxSubarrayResult; if (otherResult == null) { return(false); } return(this.MaxSum == otherResult.MaxSum); }
public static void TestSpeed() { for (int size = 1; size <= 400; size++) { //Console.Write("Element count = "); //string text = Console.ReadLine(); int elementCount = size; // int.Parse(text); int repeatCount = 12; int minValue = -100; int maxValue = 100; Random random = new Random(); for (int repeatIndex = 0; repeatIndex < repeatCount; repeatIndex++) { int[] data = new int[elementCount]; for (int elemIndex = 0; elemIndex < elementCount; elemIndex++) { data[elemIndex] = random.Next(minValue, maxValue); } //string dataStr = string.Join(", ", data); //Debug.Print(dataStr); MaxSubarrayResult resultBruteForce = RunWithSpeedDetails(SolveBruteForce, data, "brute force"); MaxSubarrayResult resultRecursive = RunWithSpeedDetails(SolveRecursive, data, "recursive"); MaxSubarrayResult resultLinear = RunWithSpeedDetails(SolveLinear, data, "linear"); Debug.Assert(resultRecursive.Equals(resultLinear)); Debug.Assert(resultRecursive.Equals(resultBruteForce)); string file = @"C:\Temp\MaxSubarray.csv"; string fieldDelim = ";"; string line = $"{data.Length}{fieldDelim}{resultBruteForce.TimeElapsed}{fieldDelim}{resultRecursive.TimeElapsed}{fieldDelim}{resultLinear.TimeElapsed}"; if (!File.Exists(file)) { File.AppendAllLines(file, new[] { $"Elems{fieldDelim}Brute force{fieldDelim}Recursive{fieldDelim}Linear" }); } File.AppendAllLines(file, new[] { line }); Debug.Print(""); } } }
static MaxSubarrayResult RunWithSpeedDetails(Func <int[], MaxSubarrayResult> func, int[] data, string funcName) { Stopwatch sw = Stopwatch.StartNew(); MaxSubarrayResult result = func(data); result.TimeElapsed = sw.ElapsedTicks; string text = $"max: {result.MaxSum}, {result.StartIndex} - {result.EndIndex}"; //Debug.Print(text); Debug.Print($"{data.Length} items {funcName}: {result.TimeElapsed} ticks"); return(result); }