Skip to content

Instantly share code, notes, and snippets.

@foliveira
Forked from duarten/LazyQsort.clj
Created June 28, 2011 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foliveira/1051515 to your computer and use it in GitHub Desktop.
Save foliveira/1051515 to your computer and use it in GitHub Desktop.
A lazy quick sort
public static IEnumerable<T> LazyQsort<T>(IEnumerable<T> seq, Func<T, T, bool> comp)
{
if (seq.Any() == false)
{
return Enumerable.Empty<T>();
}
var pivot = seq.First();
var xs = seq.Skip(1);
return LazyQsort(xs.Where(x => comp (x, pivot)), comp)
.Union(new[] { pivot })
.Union(LazyQsort(xs.Where(x => !comp (x, pivot)), comp));
}
@foliveira
Copy link
Author

By using Enumerable.Empty<T>() you avoid a new initialisation everytime new T[0] gets called.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment