A very simple QuickSort implemented with LINQ.
Since we use IEnumerable<int>
it doesn't matter if you work with a List<int>
or an int[]
array.
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleAppQSortLinq
{
class Program
{
static void Main(string[] args)
{
var dataSource = Enumerable.Range(0, 1000).Reverse().ToList(); // 999, 998, ... 0
var dataSorted = QuickSortLinq(dataSource); // 0, 1, ... 999
foreach(var n in dataSorted)
{
Console.WriteLine(n);
}
Console.ReadKey();
}
public static IEnumerable<int> QuickSortLinq(IEnumerable<int> source)
{
if (!source.Any())
return source;
int first = source.First();
return source
.GroupBy(i => i.CompareTo(first))
.OrderBy(g => g.Key)
.SelectMany(g => g.Key == 0 ? g : QuickSortLinq(g));
}
}
}
Notice: While the performance is not slow, the use of OrderBy
in conjunction with IComparer
is definitely faster.