using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Sort { ////// http://en.wikipedia.org/wiki/Heapsort /// class HeapSort1 { public HeapSort1() { Console.WriteLine("==============================================="); Console.WriteLine("O(n log n)"); } ////// 小根堆排序 /// /// /// /// private static void HeapSort(ref double[] dblArray) { for (int i = dblArray.Length - 1; i >= 0; i--) { if (2 * i + 1 < dblArray.Length) { int MinChildrenIndex = 2 * i + 1; //比较左子树和右子树,记录最小值的Index if (2 * i + 2 < dblArray.Length) { if (dblArray[2 * i + 1] > dblArray[2 * i + 2]) MinChildrenIndex = 2 * i + 2; } if (dblArray[i] > dblArray[MinChildrenIndex]) { ExchageValue(ref dblArray[i], ref dblArray[MinChildrenIndex]); NodeSort(ref dblArray, MinChildrenIndex); } } } } ////// 节点排序 /// /// /// private static void NodeSort(ref double[] dblArray, int StartIndex) { while (2 * StartIndex + 1 < dblArray.Length) { int MinChildrenIndex = 2 * StartIndex + 1; if (2 * StartIndex + 2 < dblArray.Length) { if (dblArray[2 * StartIndex + 1] > dblArray[2 * StartIndex + 2]) { MinChildrenIndex = 2 * StartIndex + 2; } } if (dblArray[StartIndex] > dblArray[MinChildrenIndex]) { ExchageValue(ref dblArray[StartIndex], ref dblArray[MinChildrenIndex]); StartIndex = MinChildrenIndex; } } } ////// 交换值 /// /// /// private static void ExchageValue(ref double A, ref double B) { double Temp = A; A = B; B = Temp; } } }
Heap Sort
最新推荐文章于 2021-06-15 13:40:41 发布