Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is time complexity of LINQ Order()/OrderBy() followed by Take(k)?

What is the time complexity of the following code in C#?

array.Order().Take(k).ToArray();

Will LINQ treat this as QuickSelect? Or, will it perform full array sorting with the complexity O(n log n)?

like image 932
Andrei Avatar asked Oct 26 '25 04:10

Andrei


1 Answers

This behaviour is not guaranteed by the documentation. However, the current implementation uses a partial QuickSort for .OrderBy().Skip/Take, and a QuickSelect for .OrderBy().First/Last/ElementAt.

This means that the time complexity for .OrderBy().Take(k) is O(n + k log k) Average and O(n²) Worst.

This was implemented in this pull request, back in 2016 (meaning that this was in .NET Core 1.0). This was a deliberate optimisation which was added some time ago, meaning that there is very little chance of it being removed, in practice.

like image 133
canton7 Avatar answered Oct 27 '25 20:10

canton7



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!