调整是从(arr.length-1) / 2开始,即最后一个节点的父节点开始调整成堆
public class Heap{ /** * 一次堆排序调整 * @param a 调整的数组 * @param pos 调整的初始元素位置 * @param len 调整的最后一个元素位置 */ public static void minAdjust(int[] arr, int pos, int len){ int tmp, child; //pos * 2 + 1 <= len判断是否与子节点,注意是 (<= ) tmp = child调整子节点 for(tmp = arr[pos]; pos * 2 + 1 <= len; pos = child){ child = pos * 2 + 1; //子节点位置 //有两个子节点,且小的在后一个位置 if(child < len && arr[child] > arr[child+1]){ child ++; } //子节点小于父节点的情况下,子节点移动到父节点的位置 if(arr[child] < tmp){ arr[pos] = arr[child]; }else{ break; } } arr[child] = tmp; } public static void minHeap(int[] arry){ int len = arry.length; //建立小根堆 for(int i= len / 2 -1; i >= 0 ; i--){ minAdjust(arry, i, len-1); } //交换堆顶元素与堆最后一个元素,形成有序数组 for(int i= len-1; i>=0; i--){ int tmp = arry[0]; arry[0] = arry[i]; arry[i] = tmp; minAdjust(arry, 0, i-1); } } }