Feb 22, 2008

Quick Sort (Haskell vs C#)

A function for Quick Sort.

C#

static int[] QuickSort(int[] a, int c)
{
if (a.Length == 0) return a;
if (c == 0) return a;

int p = a[0];

int l = 0;
int h = 0;
int[] lo = new int[a.Length];
int[] hi = new int[a.Length];

for (int i = 1; i < c; i++)
{
if (a[i] < p)
{
lo[l++] = a[i];
}
else
{
hi[h++] = a[i];
}
}

lo = QuickSort(lo, l);
lo[l++] = p;
hi = QuickSort(hi, h);
for (int i = 0; l < lo.Length; i++)
{
lo[l++] = hi[i];
}

return lo;
}

Too difficult.


Haskell

qsort [] = []
qsort (p:xs) = qsort lt ++ [p] ++ qsort gteq
where
lt = [x | x <- xs, x < p]
gteq = [x | x <- xs, x >= p]

Very simple.


C# with Enumerable

static IEnumerable QuickSort(IEnumerable a)
{
if (a.Count() == 0) return a;

int p = a.First();
var xs = a.Skip(1);
var lo = xs.Where(y => y < p);
var hi = xs.Where(y => y >= p);

return QuickSort(lo).Concat(new[] { p }).Concat(QuickSort(hi));
}

This code get close to Haskell's one.

1 comment:

Anonymous said...

Why not use filter instead of list comprehension in the Haskell command?

qsort [] = []
qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)

I guess filter simply hides the comprehension behind a higher level function but it does make shorter code!