Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What sorting algorithm does the .NET framework implement [duplicate]

Could anyone please advise when implementing something like IComparable in .NET what sorting algorithm does .NET use to actually sort the underlying data? Also is the algorithm used customizable or selectable?

like image 778
Maxim Gershkovich Avatar asked May 11 '11 03:05

Maxim Gershkovich


2 Answers

There are two biggies.

Array.Sort (which sorts an array in-place) uses an unstable Quicksort.

This is the same implementation used internally by List<T>.Sort, according to the MSDN documentation:

This method uses Array.Sort, which uses the QuickSort algorithm.

The Enumerable.OrderBy<TSource, TKey> method (which sorts a copy of an input sequence) uses a stable Quicksort.

As far as I know, these are the only two sorting implementations in the .NET BCL.

like image 166
Dan Tao Avatar answered Sep 29 '22 12:09

Dan Tao


The MSDN Documentation states that the sorting algorithm used is Quicksort (at least for arrays) - This is not selectable or customizable.

Note that its not the IComparable interface that specifies what sorting method to use, its down to the method or class that is doing the sorting (normally an array or list, but it could be any method), for example its completely possible for arrays and Lists to sort using completely different algorithms (although in reality both use Quicksort)

This means that if you really want to you can implement your own sorting method using an alternative algorithm.

like image 34
Justin Avatar answered Sep 29 '22 14:09

Justin