private static void Sort <TSource>(IList <TSource> tmp, IList <TSource> src, IComparer <TSource> comparer, int lo, int hi) { if (hi <= lo) { return; } if (lo + hi <= Threshold) { for (var i = lo + 1; i <= hi; i++) { for (var j = i; j > 0 && comparer.Less(src[j], src[j - 1]); j--) { src.Swap(j, j - 1); } } } else { var mid = lo + (hi - lo) / 2; Sort(tmp, src, comparer, lo, mid); Sort(tmp, src, comparer, mid + 1, hi); if (!comparer.Less(src[mid], src[mid + 1])) { MergeInternal(tmp, src, comparer, lo, mid, hi); } } }
private static void MergeInternal <TSource>(IList <TSource> tmp, IList <TSource> src, IComparer <TSource> comparer, int lo, int mid, int hi) { var i = lo; var j = mid + 1; for (var k = lo; k <= hi; k++) { tmp[k] = src[k]; } for (var k = lo; k <= hi; k++) { if (i > mid) { src[k] = tmp[j++]; } else if (j > hi) { src[k] = tmp[i++]; } else if (comparer.Less(tmp[j], tmp[i])) { src[k] = tmp[j++]; } else { src[k] = tmp[i++]; } } }
private Node <T> Merge(Node <T> left, Node <T> right, IComparer <T> comp) { Node <T> result = null; if (left == null) { return(right); } if (right == null) { return(left); } if (comp.Less(left.Item, right.Item)) { result = left; result.Next = Merge(left.Next, right, comp); } else { result = right; result.Next = Merge(left, right.Next, comp); } return(result); }
public static void Sort <TSource>(IList <TSource> arr, IComparer <TSource> comparer) { for (var i = 1; i < arr.Count; i++) { for (var j = i; j > 0 && comparer.Less(arr[j], arr[j - 1]); j--) { arr.Swap(j, j - 1); } } }
private static void SortWithHalfExch <TSource>(IList <TSource> arr, IComparer <TSource> comparer) { for (var i = 2; i < arr.Count; i++) { var tmp = arr[i]; var j = i; while (comparer.Less(tmp, arr[j - 1])) { arr[j] = arr[j - 1]; j--; } arr[j] = tmp; } }
private static int CreateSentinel <TSource>(IList <TSource> arr, IComparer <TSource> comparer) { var exchanges = 0; for (var i = arr.Count - 1; i > 0; i--) { if (comparer.Less(arr[i], arr[i - 1])) { arr.Swap(i, i - 1); exchanges++; } } return(exchanges); }
public static void Sort <TSource>(IList <TSource> arr, IComparer <TSource> comparer) { for (var i = 0; i < arr.Count; i++) { var min = i; for (var j = i + 1; j < arr.Count; j++) { if (comparer.Less(arr[j], arr[min])) { min = j; } } arr.Swap(i, min); } }
public static void Sort <TSource>(IList <TSource> arr, IComparer <TSource> comparer) { var h = ComputeH(arr.Count); while (h >= 1) { for (var i = h; i < arr.Count; i++) { for (var j = i; j >= h && comparer.Less(arr[j], arr[j - h]); j -= h) { arr.Swap(j, j - h); } } h /= 3; } }
private static void Sort <TSource>(IList <TSource> tmp, IList <TSource> src, IComparer <TSource> comparer, int lo, int hi) { if (hi <= lo) { return; } var mid = lo + (hi - lo) / 2; Sort(tmp, src, comparer, lo, mid); Sort(tmp, src, comparer, mid + 1, hi); if (!comparer.Less(src[mid], src[mid + 1])) { MergeInternal(tmp, src, comparer, lo, mid, hi); } }