1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| public static class SortingSupport { public delegate bool CompareLess<T>(T t1, T t2);
static void Swap<T>(T[] a, int i, int j) { T temp = a[i]; a[i] = a[j]; a[j] = temp; }
#region 堆排序 public static void HeapSort<T>(T[] a, CompareLess<T> cp) { int heapsize = a.Length; BuildMinHeap(a, cp); for (int i = a.Length; i > 1; i--) { Swap(a, 0, i - 1); heapsize--; MinHeapify(a, 1, heapsize, cp); } }
static void BuildMinHeap<T>(T[] a, CompareLess<T> cp) { int heapSize = a.Length; for (int i = a.Length / 2; i > 0; i--) MinHeapify(a, i, heapSize, cp); }
static void MinHeapify<T>(T[] a, int i, int heapSize, CompareLess<T> cp) { int l = i << 1; int r = (i << 1) + 1; int min_pos = -1; if (l <= heapSize && cp(a[l - 1], a[i - 1])) min_pos = l; else min_pos = i; if (r <= heapSize && cp(a[r - 1], a[min_pos - 1])) min_pos = r; if (min_pos != i) { Swap(a, min_pos - 1, i - 1); MinHeapify(a, min_pos, heapSize, cp); } } #endregion }
|