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