diff --git a/BounceSort/BounceSort.cs b/BounceSort/BounceSort.cs index 12fa956..8182e8b 100644 --- a/BounceSort/BounceSort.cs +++ b/BounceSort/BounceSort.cs @@ -1,63 +1,94 @@ -namespace BounceSort +using System.Diagnostics; + +namespace BounceSort { public class BounceSort { public static void Main() { - int[] array = { 5, 8, 2, 1, 6, 3, 7, 4 }; + int[] array = GenerateRandomArray(length: 10000); + Console.WriteLine(value: "Unsorted Array:"); PrintArray(array: array); + + Stopwatch stopwatch = new(); + stopwatch.Start(); + BounceSortArray(array: array); + + stopwatch.Stop(); + Console.WriteLine(value: "Sorted Array:"); PrintArray(array: array); + + Console.WriteLine(value: $"Sort time: {stopwatch.ElapsedMilliseconds} milliseconds"); } - public static void BounceSortArray(int[] array) + private static void BounceSortArray(T[] array) where T : IComparable { int n = array.Length; int left = 0; int right = n - 1; + while (left < right) { int newRight = left; int newLeft = right; + for (int i = left; i < right; i++) { - if (array[i] > array[i + 1]) + if (array[i].CompareTo(other: array[i + 1]) > 0) { - Swap(array: array, i, i + 1); + Swap(array: array, i: i, j: i + 1); newRight = i; } } + right = newRight; + for (int i = right; i > left; i--) { - if (array[i] < array[i - 1]) + if (array[i].CompareTo(other: array[i - 1]) < 0) { - Swap(array: array, i, i - 1); + Swap(array: array, i: i, j: i - 1); newLeft = i; } } + left = newLeft; } } - public static void Swap(int[] array, int i, int j) + private static void Swap(T[] array, int i, int j) { if (i == j) { return; } + (array[j], array[i]) = (array[i], array[j]); } - public static void PrintArray(int[] array) + private static void PrintArray(T[] array) { - foreach (int element in array) + foreach (T element in array) { - Console.Write(value: element + " "); + Console.Write(value: $"{element} "); } Console.WriteLine(); } + + private static int[] GenerateRandomArray(int length) + { + Random random = new(); + int[] array = new int[length]; + + for (int i = 0; i < length; i++) + { + array[i] = random.Next(maxValue: 1000); + } + + return array; + } } } \ No newline at end of file