What Sorting Algorithm Is Used By LINQ "OrderBy"?

LinqAlgorithmSortingQuicksort

Linq Problem Overview


Evidently LINQ's "OrderBy" had originally been specified as unstable, but by the time of Orca it was specified as stable. Not all documentation has been updated accordingly - consider these links:

But if LINQ's OrderBy is now "stable," then it means it is not using a quicksort (which is inherently unstable) even though some documentation (e.g. Troy's book) says it is. So my question is: if not quicksort, then what is the actual algorithm LINQ's orderBy is using?

Linq Solutions


Solution 1 - Linq

For LINQ to Objects, it's a stable quicksort that is used. For any other kind of LINQ, it's left to the underlying implementation.

Solution 2 - Linq

Boot up reflector, open to System.Linq.EnumerableSorter reveals that Linq2Objects uses the quick sort

Solution 3 - Linq

Quicksort is used, but the reason why it is stable is because the indices of each pair of elements are compared if all the keys test equal.

In other words, you can make any quicksort stable by including in the comparator function a comparison of the original indices of the two elements as a fallback.

Source: http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,1395017e067e5a34

Solution 4 - Linq

I am under the understanding that OrderBy gets translated into SQL that performs the sort on the Database. At least in the case of LINQ to SQL

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrent AriasView Question on Stackoverflow
Solution 1 - LinqJb EvainView Answer on Stackoverflow
Solution 2 - LinqLorenVSView Answer on Stackoverflow
Solution 3 - LinqWesner MoiseView Answer on Stackoverflow
Solution 4 - LinqJohn WeldonView Answer on Stackoverflow