# Generic Quick 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 `QuickSort`

to perform a quick sort on an array of T:

using System; using System.Collections.Generic; class Program { static void Main(string[] args) { var numbers = new int[] { 5, 4, 5, 7, 6, 9, 4, 1, 1, 3, 4, 50, 56, 41 }; QuickSort(numbers); PrintList(numbers); Console.ReadKey(); } private static void QuickSort<T>(T[] list) where T : IComparable { QuickSortInternal(list, 0, list.Length - 1); } private static void QuickSortInternal<T>(T[] list, int left, int right) where T : IComparable { if(left >= right) { return; } int partition = PartitionInternal(list, left, right); QuickSortInternal(list, left, partition - 1); QuickSortInternal(list, partition + 1, right); } private static int PartitionInternal<T>(T[] list, int left, int right) where T : IComparable { T partition = list[right]; // stack items smaller than partition from left to right int swapIndex = left; for (int i = left; i < right; i++) { T item = list[i]; if(item.CompareTo(partition) <= 0) { list[i] = list[swapIndex]; list[swapIndex] = item; swapIndex++; } } // put the partition after all the smaller items list[right] = list[swapIndex]; list[swapIndex] = partition; return right; } 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`

interface, you can perform the quick sort algorithm without knowing the exact type you are working with.

If you want to understand the logic behind the quick 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~