Wednesday , 26 April 2017
Home » QuickSort in Functional C#

QuickSort in Functional C#

Here’s a very simple QuickSort algorithm from Wikipedia written in a very Functional way of C#. Notice that it looks very close to the pseudo-code algorithm shown in Wikipedia. The pivot used is just sequence.First(). You can replace the pivot by some random position if you wish.

I tried making this more fun by using the Fix Point Generator which I mentioned previously, and converted that code into a Func<IEnumerable<T>> instead. Here’s the code.

This is a perfect example of how you can use the Fix Point Generator to create your recursive functions on the fly. If you want to make it reusable with an extension method, you can easily convert it to the extension method, or a normal method. Personally I feel that using the Fix Point Generator is more intuitive and slightly more readable as oppose to the extension method way of doing things.

One point to note is that the “Concat” extension only accepts an IEnumerable<T> and not a single item. You can solve this by the above, “new[] { sequence.First() }” which is a cleaner way if you don’t want to write your own extension method (which you could too).

Crazy stuff eh?

About Justin Lee

Check Also

Samsung Galaxy Note7 – “Eye-ing” the Next Evolution in the Galaxy Note Series

The next generation Samsung Galaxy Note7 combines both style and innovative features and top of …

Leave a Reply