Generic Insertion Sort in C# .NET
Niels Swimberghe - - .NET
Follow me on Twitter, buy me a coffee
Early this year, I decided to brush up on my algorithms and data structure knowledge. I took these great two courses (1, 2) on PluralSight by Robert Horvick.
To practice what I learned in this course, I decided to create generic versions of the different algorithms and data structures.
What do I mean by generic versions? These types of courses always use integers or strings to demonstrate the algorithms. Instead of using those primitive data types, I'm reimplementing the algorithms and data structures using C#'s generic type parameters.
Here's a console application with a generic method InsertionSort
to perform an insertion sort on an enumerable:
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> { 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; } } } return sortedList; } private static void PrintList<T>(IEnumerable<T> list) { foreach (var item in list) { Console.WriteLine(item); } } }
By using a generic type parameter with the constraint that the type has to implement the IComparable<T>
(or IComparable
) interface, you can perform the insertion sort algorithm without knowing the exact type you are working with.
If you want to understand the logic behind the insertion sort algorithm, I recommend checking out the courses mentioned earlier. There's also a lot of other great resources out there online!
Disclaimer: This code works, but is only developed for the sake of practice. Use at your own risk or just use a sorting library. If you see some room for improvement, there most likely is, I'm all ears~