Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Quicksort is Unstable Except When Cascading

Tags:

sorting

linq

On page 64 of "LINQ To Objects Using C# 4.0" (Tony Magennis) he states that LINQ's quicksort ordering algorithm is unstable...

...although this is simply solved by cascading the result into a ThenBy or ThenByDescending operator.

Huh? Why would cascading an unstable sortation into another sortation fix the result? In fact, I'd say that isn't possible. The original order, once passed through an unstable sort, is simply lost. What am I missing here?

like image 650
Brent Arias Avatar asked May 07 '10 07:05

Brent Arias


People also ask

Why QuickSort is unstable?

QuickSort is an unstable algorithm because we do swapping of elements according to pivot's position (without considering their original positions).

Which sorting algorithm does Linq use?

For LINQ to Objects, it's a stable quicksort that is used.


1 Answers

Put simply, he's wrong. The Linq OrderBy et al. methods are documented as performing a stable sort:

This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved. In contrast, an unstable sort does not preserve the order of elements that have the same key.

like image 127
Greg Beech Avatar answered Sep 20 '22 11:09

Greg Beech