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/0527c8c423fd863cd2e4af630b8e672b to your computer and use it in GitHub Desktop.
Save Swimburger/0527c8c423fd863cd2e4af630b8e672b to your computer and use it in GitHub Desktop.
Generic Insertion 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 = InsertionSort(randomNumbers);
Console.WriteLine("Insertion Sort:");
PrintList(sortedNumbers);
Console.ReadKey();
}
private static IEnumerable<T> InsertionSort<T>(IEnumerable<T> list) where T : IComparable
{
T[] sortedList = list.ToArray();
int listLength = sortedList.Length;
for (int i = 1; i < listLength; i++)
{
for (int previousItemIndex = i - 1; previousItemIndex > -1; previousItemIndex--)
{
int currentItemIndex = previousItemIndex + 1;
T currentItem = sortedList[currentItemIndex];
T previousItem = sortedList[previousItemIndex];
var comparison = previousItem.CompareTo(currentItem);
if (comparison > 0)
{
sortedList[previousItemIndex] = currentItem;
sortedList[currentItemIndex] = previousItem;
}
else
{
break;
}
// for debugging
// Console.Clear();
// PrintList(sortedList);
}
}
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