Last active
January 27, 2021 21:20
-
-
Save Swimburger/6efeff7b7f070912e061d0ef776e2c7c to your computer and use it in GitHub Desktop.
Generic Bubble Sort in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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