Skip to content

Instantly share code, notes, and snippets.

@battermann
Created April 15, 2016 22:16
Show Gist options
  • Save battermann/33774337f5a2aa47a81358ef79e1c163 to your computer and use it in GitHub Desktop.
Save battermann/33774337f5a2aa47a81358ef79e1c163 to your computer and use it in GitHub Desktop.
Recursive implementation of QuickSort in C#. It's really slow and absolutely not recommended to use it!! It's only meant for demonstration purposes.
static class Program
{
static void Main(string[] args)
{
var list = new List<int> {4, 5, 4, 7, 9, 1, 6, 1, 0, -99, 10000, 3, 2};
var sorted = list.QuickSort();
Console.WriteLine(String.Join(", ", sorted));
// output: -99, 0, 1, 1, 2, 3, 4, 4, 5, 6, 7, 9, 10000
}
/// <summary>
/// Recursive implementation of QuickSort. It's really slow and absolutely not recommended to use it!! It's only meant for demonstration purposes.
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public static List<int> QuickSort(this List<int> list)
{
return !list.Any()
? list
: list.Skip(1)
.Where(x => x <= list.First())
.ToList()
.QuickSort()
.Concat(new List<int> { list.First() })
.Concat(list.Skip(1)
.Where(x => x > list.First())
.ToList()
.QuickSort())
.ToList();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment