Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the time complexity of Linq OrderBy().ThenBy() method sequence?

I am using Linq and Lambda Operations in my projects and I needed to sort a List according to two properties of a class. Therefore, I used OrderBy().ThenBy() methods as below:

class ValueWithIndex{     public long Value;     public int Index; } ...  List<ValueWithIndex> valuesWithIndex = new List<ValueWithIndex>();  for (int i = 0; i < A.Length; i++){     ValueWithIndex vi = new ValueWithIndex();     vi.Value = A[i];     vi.Index = i;     valuesWithIndex.Add(vi); } var orderedValues = valuesWithIndex.OrderBy(v => v.Value).ThenBy(v => v.Index);  ... 

In This answer, it is explained that, OrderBy() uses Quicksort, so even if it has O(N*logN) average time complexity, for the worst case, time complexity is around O(N2). If also ThenBy() method has a worst time complexity of O(N2), it would be pointless to use these methods.

Is ThenBy() method use Quicksort, too? If yes, does it mean that for the same "v.Value"s, "v.Index"es are sorted with O(N2) worst time complexity?

like image 385
tuncay altınpulluk Avatar asked Dec 18 '16 21:12

tuncay altınpulluk


People also ask

What is difference between OrderBy and ThenBy in LINQ?

The OrderBy() Method, first sort the elements of the sequence or collection in ascending order after that ThenBy() method is used to again sort the result of OrderBy() method in ascending order.

What is OrderBy in LINQ?

Sorts the elements of a sequence in ascending order according to a key. OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>) Sorts the elements of a sequence in ascending order by using a specified comparer.

How does OrderBy and ThenBy work?

The ThenBy and ThenByDescending extension methods are used for sorting on multiple fields. The OrderBy() method sorts the collection in ascending order based on specified field. Use ThenBy() method after OrderBy to sort the collection on another field in ascending order.

What algorithm does LINQ OrderBy use?

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


1 Answers

The LINQ OrderBy(...).ThenBy(...)...ThenBy(...) method chain form a single sort operation by multiple sort keys (using multi key comparer).

Thus, regardless of how many ThenBy(Descending) methods do you include in the chain, the time complexity of the sort operation stays the typical for QuickSort O(N*logN) average / O(N2) worst case. Of course more keys you add, comparing two objects will take more time, but the complexity of the sort operation would not change.

like image 110
Ivan Stoev Avatar answered Sep 22 '22 22:09

Ivan Stoev