问题
What is time complexity of C#'s List<T>.Sort()
I guess it's o(N)
But after I searched a lot, I didn't get any accurate result.
回答1:
http://msdn.microsoft.com/en-us/library/b0zbh7b6.aspx
This method uses Array.Sort, which uses the QuickSort algorithm. This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.
On average, this method is an O(n log n) operation, where n is Count; in the worst case it is an O(n ^ 2) operation.
回答2:
From the documentation:
On average, this method is an O(n log n) operation, where n is Count; in the worst case it is an O(n ^ 2) operation.
This is because it uses Quicksort. While this is typically O(n log n), as mentioned on Wikipedia, "Quicksort is often faster in practice than other O(n log n) algorithms"
回答3:
Adding some information from the recent addition to MSDN on this topic, for framework 4.5, List.Sort method uses a different Sort Strategy depending on the number of elements and partitions.
This method uses the Array.Sort method which applies the introspective sort as follows:
- If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.
- If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.
- Otherwise, it uses a Quicksort algorithm.
This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.
On average, this method is an O(n log n) operation, where n is Count; in the worst case it is an O(n ^ 2) operation.
回答4:
best it can be asymptotically is O(nlogn)
来源:https://stackoverflow.com/questions/9612167/what-is-time-complexity-of-net-list-sort