C# list sort底層原理


如果提供比較,則使用委托表示的方法對列表中的元素進行排序。如果comparison為null,則拋出ArgumentNullException。

此方法使用數組.排序,其應用自省排序,如下所示:

如果分區大小小於或等於16個元素,則使用插入排序算法

如果分區數超過2logn,其中n是輸入數組的范圍,則使用Heapsort算法。

否則,它將使用快速排序算法。

這個實現執行不穩定的排序;也就是說,如果兩個元素相等,它們的順序可能不會被保留。相反,穩定排序保留相等元素的順序。

此方法是一個O(n logn)操作,其中n是Count。

 

官網文檔:

https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.sort?redirectedfrom=MSDN&view=net-5.0#System_Collections_Generic_List_1_Sort_System_Comparison__0__

Remarks

If comparison is provided, the elements of the List<T> are sorted using the method represented by the delegate.

If comparison is null, an ArgumentNullException is thrown.

This method uses Array.Sort, which applies the introspective sort as follows:

  • If the partition size is less than or equal to 16 elements, it uses an insertion sort algorithm

  • If the number of partitions exceeds 2 log n, 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.

This method is an O(n log n) operation, where n is Count.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM