PageRenderTime 44ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/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
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Delta.Utilities.Collections
  4. {
  5. /// <summary>
  6. /// Sort helper
  7. /// </summary>
  8. public static class SortHelper
  9. {
  10. #region StableSort (Static)
  11. /// <summary>
  12. /// A stable insertion sort implementation.
  13. /// This method can be used instead of the .NET Sort when stable sorting
  14. /// is needed because the .NET implementation of sorting is unstable.
  15. /// Note that this method implements insertion sort which is
  16. /// asymptotically less efficient than .NET Sort
  17. /// (O(nlogn) QuickSort algorithm).
  18. /// More info: http://www.csharp411.com/c-stable-sort/
  19. /// </summary>
  20. /// <typeparam name="T">The type of the elements to sort</typeparam>
  21. /// <param name="list">The list with the elements to sort</param>
  22. /// <param name="comparison">The comparison function</param>
  23. public static void StableSort<T>(this IList<T> list,
  24. Comparison<T> comparison)
  25. {
  26. // Insertion sort
  27. int count = list.Count;
  28. for (int j = 1; j < count; j++)
  29. {
  30. T key = list[j];
  31. int i = j - 1;
  32. for (; i >= 0 && comparison(list[i], key) > 0; i--)
  33. {
  34. list[i + 1] = list[i];
  35. }
  36. list[i + 1] = key;
  37. } // for
  38. }
  39. #endregion
  40. }
  41. }