public void HeapSort(int[] data) {//创建大顶堆for (int i = 0; i < data.Length; ++i){Add(data, i);}//开始排序for (int i = data.Length - 1; i >= 0; --i){int mark = data[i];data[i] = data[0];data[0] = mark;CheckHeap(data,0,i-1);}Console.WriteLine(data);}public void Add(int[] heap,int idx) {int father = (idx - 1) / 2;if (father >= 0 && heap[idx] > heap[father]) {//如果父节点比本节点小,则交换int mark = heap[idx];heap[idx] = heap[father];heap[father] = mark;//交换之后继向上迭代Add(heap,father);}}public void CheckHeap(int[] heap,int idx,int len) {//限制边界,当把堆顶的元素放到最后时,堆的大小就变为了原堆大小 - 1int left = (2 * idx + 1 > len) ?idx: (2 * idx + 1);int right = (2 * idx + 2 > len) ? idx : (2 * idx + 2);bool _change = heap[idx] < Math.Max(heap[left],heap[right]);if (_change) {if (Math.Max(heap[left], heap[right]) == heap[left]){//找出子节点中最大的一个,并交换int mark = heap[idx];heap[idx] = heap[left];heap[left] = mark;//交换后继续向下迭代,直到限制的边界,也就是此时堆的大小CheckHeap(heap, left, len);}else {int mark = heap[idx];heap[idx] = heap[right];heap[right] = mark;CheckHeap(heap, right, len);}}}
