Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
- added timing, random number generation and generic integer types
  • Loading branch information
mjohne authored Jul 3, 2023
1 parent f6a94d7 commit 7f42567
Showing 1 changed file with 42 additions and 11 deletions.
53 changes: 42 additions & 11 deletions BounceSort/BounceSort.cs
Original file line number Diff line number Diff line change
@@ -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>(T[] array) where T : IComparable<T>
{
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>(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>(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;
}
}
}

0 comments on commit 7f42567

Please sign in to comment.