Skip to content

Instantly share code, notes, and snippets.

@Swimburger
Last active January 27, 2021 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Swimburger/6efeff7b7f070912e061d0ef776e2c7c to your computer and use it in GitHub Desktop.
Save Swimburger/6efeff7b7f070912e061d0ef776e2c7c to your computer and use it in GitHub Desktop.
Generic Bubble Sort in C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var randomNumbers = new int[] { 5, 4, 5, 7, 6, 9, 4, 1, 1, 3, 4, 50, 56, 41 };
var sortedNumbers = BubbleSort(randomNumbers);
PrintList(sortedNumbers);
Console.ReadKey();
}
private static IEnumerable<T> BubbleSort<T>(IEnumerable<T> list) where T : IComparable
{
T[] sortedList = list.ToArray();
int listLength = sortedList.Length;
while (true)
{
bool performedSwap = false;
for (int currentItemIndex = 1; currentItemIndex < listLength; currentItemIndex++)
{
int previousItemIndex = currentItemIndex - 1;
T previousItem = sortedList[previousItemIndex];
T currentItem = sortedList[currentItemIndex];
var comparison = previousItem.CompareTo(currentItem);
if (comparison > 0)
{
sortedList[previousItemIndex] = currentItem;
sortedList[currentItemIndex] = previousItem;
performedSwap = true;
}
}
// for debugging
//Console.Clear();
//PrintList(sortedList);
if (!performedSwap)
{
break;
}
}
return sortedList;
}
private static void PrintList<T>(IEnumerable<T> list)
{
foreach (var item in list)
{
Console.WriteLine(item);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment