/Utilities/Collections/SortHelper.cs
C# | 43 lines | 25 code | 2 blank | 16 comment | 3 complexity | c46234f2282cc78bfc9035ff141c664f MD5 | raw file
Possible License(s): Apache-2.0
- using System;
- using System.Collections.Generic;
-
- namespace Delta.Utilities.Collections
- {
- /// <summary>
- /// Sort helper
- /// </summary>
- public static class SortHelper
- {
- #region StableSort (Static)
- /// <summary>
- /// A stable insertion sort implementation.
- /// This method can be used instead of the .NET Sort when stable sorting
- /// is needed because the .NET implementation of sorting is unstable.
- /// Note that this method implements insertion sort which is
- /// asymptotically less efficient than .NET Sort
- /// (O(nlogn) QuickSort algorithm).
- /// More info: http://www.csharp411.com/c-stable-sort/
- /// </summary>
- /// <typeparam name="T">The type of the elements to sort</typeparam>
- /// <param name="list">The list with the elements to sort</param>
- /// <param name="comparison">The comparison function</param>
- public static void StableSort<T>(this IList<T> list,
- Comparison<T> comparison)
- {
- // Insertion sort
- int count = list.Count;
- for (int j = 1; j < count; j++)
- {
- T key = list[j];
-
- int i = j - 1;
- for (; i >= 0 && comparison(list[i], key) > 0; i--)
- {
- list[i + 1] = list[i];
- }
- list[i + 1] = key;
- } // for
- }
- #endregion
- }
- }