Onorio Catenacci
Onorio Catenacci

Reputation: 15313

How To Eliminate Redundant Code In These Functions?

I've written some timing code for instructional purposes. One set of code uses a bubble sort (demonstrates O(n^2) complexity) and the other uses quick sort (O(n log n)). The function signatures differ; my bubble sort takes an int array and returns an int array while the quicksort takes an int array and modifies it in place--void return. So this is the code I've gotten to time the operation:

    private delegate int[] ArrayFunc(int[] arr);
    private delegate void AlternateArrayFunc(int[] arr, int lbound, int ubound);

    private static long TimeOperation(ArrayFunc functionToTest,int[] arrayToSort, int[] correctResult) 
    {
        var stopwatch = new Stopwatch();
        stopwatch.Start();
        int[] resultArray = functionToTest.Invoke(arrayToSort);
        stopwatch.Stop();
        Debug.Assert(resultArray.SequenceEqual(correctResult), "Arrays do not match");
        return stopwatch.ElapsedTicks;
    }

    private static long TimeOperation(AlternateArrayFunc functionToTest, int[] arrayToSort, int[] correctResult)
    {
        var stopwatch = new System.Diagnostics.Stopwatch();
        stopwatch.Start();
        functionToTest.Invoke(arrayToSort, 0, arrayToSort.Length - 1);
        stopwatch.Stop();
        Debug.Assert(arrayToSort.SequenceEqual(correctResult), "Arrays do not match");
        return stopwatch.ElapsedTicks;
    }

I want just one TimeOperation function but I can't quite figure out how to deal with the two different delegates. I tried making the first argument a generic but I can't do that with a delegate--or at least I can't figure out how to do that anyway. If I make it a generic then it balks at the .invoke I really hate to keep the code this way since the only part that's different is the actual function I'm timing.

Any suggestions of how I might follow the DRY principle in this case?

Upvotes: 0

Views: 121

Answers (1)

itsme86
itsme86

Reputation: 19496

You could create an additional method for your quick sort that has the same signature as your bubble sort method:

public int[] QuickSortEntry(int[] arr)
{
    QuickSort(arr, 0, arr.Length - 1);
    return arr;
}

Or you could even just do this:

ArrayFunc qSort = arr => { QuickSort(arr, 0, arr.Length - 1); return arr; };

...and pass that into your timer method.

Upvotes: 2

Related Questions