C# functional quicksort is failing
Posted
by Rubys
on Stack Overflow
See other posts from Stack Overflow
or by Rubys
Published on 2010-04-24T14:23:44Z
Indexed on
2010/04/24
14:33 UTC
Read the original article
Hit count: 282
I'm trying to implement quicksort in a functional style using C# using linq, and this code randomly works/doesn't work, and I can't figure out why.
Important to mention: When I call this on an array or list, it works fine. But on an unknown-what-it-really-is IEnumerable, it goes insane (loses values or crashes, usually. sometimes works.)
The code:
public static IEnumerable<T> Quicksort<T>(this IEnumerable<T> source) where T : IComparable<T> { if (!source.Any()) yield break; var pivot = source.First(); var sortedQuery = source.Skip(1).Where(a => a.CompareTo(source.First()) <= 0).Quicksort() .Concat(new[] { pivot }) .Concat(source.Skip(1).Where(a => a.CompareTo(source.First()) > 0).Quicksort()); foreach (T key in sortedQuery) yield return key; }
Can you find any faults here that would cause this to fail?
© Stack Overflow or respective owner