[Solved] How to pass method name as a parmeter? [closed]


Refactor the code that is repeated into a method that takes an Action<int[]> parameter.

Something like this (untested):

void Main()
{
    Random rnd = new Random(Guid.NewGuid().GetHashCode());
    int[] ArrayRandom = new int[200000];
    for (int j = 0; j < ArrayRandom.Length; j++) ArrayRandom[j] = rnd.Next(int.MaxValue);

    performSort("Heap Sort", ArrayRandom, HeapSort);
    performSort("Cocktail Sort", ArrayRandom, HeapSort);
    performSort("Selection Sort", ArrayRandom, HeapSort);
    performSort("Insertion Sort", ArrayRandom, HeapSort);
}

public void performSort(string sortName, int[] arrayToSort, Action<int[]> sortFunction)
{
    int[] ArrayRandom = arrayToSort;

    Console.WriteLine("\n{0}\nARRAY SIZE:\t TIME [ms]:", sortName);
    for (int u = 50000; u <= 200000; u += 10000)
    {
        int[] TestArray = new int[u];
        Array.Copy(ArrayRandom, TestArray, u);
        double ElapsedSeconds;
        long ElapsedTime = 0, MinTime = long.MaxValue, MaxTime = long.MinValue, IterationElapsedTime;
        for (int n = 0; n < (NIter + 1 + 1); ++n)
        {
            long StartingTime = Stopwatch.GetTimestamp();
            sortFunction.Invoke(TestArray);
            long EndingTime = Stopwatch.GetTimestamp();
            IterationElapsedTime = EndingTime - StartingTime;
            ElapsedTime += IterationElapsedTime;
            if (IterationElapsedTime < MinTime) MinTime = IterationElapsedTime;
            if (IterationElapsedTime > MaxTime) MaxTime = IterationElapsedTime;
        }
        ElapsedTime -= (MinTime + MaxTime);
        ElapsedSeconds = ElapsedTime * (1000.0 / (NIter * Stopwatch.Frequency));
        Console.WriteLine("{0,-12}\t{1}", u, ElapsedSeconds.ToString("F4"));
    }
}

public void HeapSort(int[] array) { //Sorting code here }
public void CocktailSort(int[] array) { //Sorting code here }
public void InsertionSort(int[] array) { //Sorting code here }
public void SelectionSort(int[] array) { //Sorting code here }

1

solved How to pass method name as a parmeter? [closed]