public class SortStopwatch
{
public delegate Task<MethodResponse> SortMethod();
private List<SortDelegate> _sortsList = new List<SortDelegate>();
private List<SortDelegate> _sortsListToShow = new List<SortDelegate>();
private int[] _array;
public SortStopwatch()
{
InitializeArray();
InitializeSortsList();
ShowMainMenu();
}
private void InitializeArray()
{
Console.WriteLine("Enter length of random array: ");
if (!int.TryParse(Console.ReadLine(), out int length) || length <= 0)
{
Console.WriteLine("Your length is incorrect! Try again");
InitializeArray();
}
_array = ArrayGenerator.GenerateRandomArray(length);
}
private void InitializeSortsList()
{
_sortsList.Add(new SortDelegate(nameof(BubbleSort),
Task.Run(async () => await SortMethodFunction(BubbleSort.Sort, (int[])_array.Clone(), nameof(BubbleSort)))));
_sortsList.Add(new SortDelegate(nameof(ChickenSort) + " (Be careful! If you add it when the array length > 50, it will take some more time to sort it)",
Task.Run(async () => await SortMethodFunction(ChickenSort.Sort, (int[])_array.Clone(), nameof(ChickenSort)))));
}
private async Task<MethodResponse> SortMethodFunction(Func<int[], Task<int[]>> function, int[] array, string methodName)
{
Stopwatch stopwatch = Stopwatch.StartNew();
var result = await function(array);
stopwatch.Stop();
return new MethodResponse()
{
Name = methodName,
Time = stopwatch.Elapsed,
Array = result
};
}
}