DCSIMG
Pretty Quick Sort With C# 3.0 - Doron's .NET Space

Pretty Quick Sort With C# 3.0

Jafar Husain writes about the prettiness of F#'s type inference, but what I really liked in his post was his C# 3.0 implementation for Quick Sort:

1 public static IEnumerable<T> QuickSort<T>(this IEnumerable<T> list) 2 where T : IComparable 3 { 4 if (!list.Any()) 5 { 6 return Enumerable.Empty<T>(); 7 } 8 var pivot = list.First(); 9 var smaller = list.Where(item => item.CompareTo(pivot) <= 0).QuickSort(); 10 var larger = list.Where(item => item.CompareTo(pivot) > 0).QuickSort(); 11 12 return smaller.Concat(new[]{pivot}).Concat(larger); 13 }

Yes, the F# implementation is more concise, but Jafar really reminded how concise can C# be as well. When I first heard about C# 3.0's var keyword, I belonged to the group that worried about code getting unreadable. Now I've grown to realize that type information can be over-rated. Sometimes it is just irrelevant noise.

Published Thursday, January 29, 2009 9:28 PM by dorony
תגים:

Comments

# re: Pretty Quick Sort With C# 3.0

Yeah, let's not pull in a two-liner Python of Haskell version, though... Hehe.

Tuesday, April 07, 2009 3:01 AM by J

# re: Pretty Quick Sort With C# 3.0

It should be noted that this is not (really) quicksort.

See augustss.blogspot.com/.../quicksort-in-haskell-quicksort-is.html

Tuesday, April 07, 2009 5:40 AM by Billy

# re: Pretty Quick Sort With C# 3.0

ps. he updated the code to prevent an infinite recursion..

Wednesday, April 08, 2009 7:47 PM by ian ross

# re: Pretty Quick Sort With C# 3.0

Hi,

This is just awesome !

I love concise code with just enough recursion to make things done !

Grats.

Tuesday, June 23, 2009 5:08 PM by Manitra

# re: Pretty Quick Sort With C# 3.0

Слабо моё имя расшифровать 5f7ce4443ca3a1ac3e669bda9276122e ?

Wednesday, October 14, 2009 1:12 AM by ноги

# re: Pretty Quick Sort With C# 3.0

>>"Yeah, let's not pull in a two-liner Python of Haskell version, though... Hehe."

nothing stop anyone to rewrite this into one string:

public static IEnumerable<T> shortQuickSort<T>(this IEnumerable<T> list) where T : IComparable<T>

       {

           return !list.Any()?Enumerable.Empty<T>():list.Skip(1).Where(item => item.CompareTo(list.First()) <= 0).qSort().Concat(new[] { list.First() }).Concat(list.Skip(1).Where(item => item.CompareTo(list.First()) > 0).qSort());

       }

Thursday, November 19, 2009 5:18 AM by kitt

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: