/**
* @author liaomengge
* 堆排序,依据完全二叉树的特性,至少只存在左节点,不存在右节点,且当i在n/2 + 1 - n之间属于叶子节点,
* 故建立最大(最小)堆,只需要在[0,(n-1)/2],注:数组下表从0开始
*
*/
public class TestDemo {
public static void main(String[] args) {
int[] arr = new int[10];
Random random = new Random();
for (int i = 0; i < arr.length; i++) {
arr[i] = random.nextInt(100);
}
display(arr);
for (int i = 0, len = arr.length; i < len; i++) {
buildMaxHead(arr, len - 1 - i);
swap(arr, 0, len - 1 - i);
}
display(arr);
}
private static void buildMaxHead(int[] arr, int headLen) {
for (int i = (headLen - 1) >> 0x01; i >= 0; i--) {
int j = i;
int largest = getLeftChild(j);
// 如果存在右节点,则找出左右最大节点的下表;否则,为左节点
if (largest < headLen) {
if (arr[largest] < arr[largest + 1]) {
largest++;
}
}
// 遍历,如果父节点小于最大子节点,则交换
while (getLeftChild(j) <= headLen && arr[largest] > arr[j]) {
swap(arr, j, largest);
j = largest;
}
}
}
private static int getLeftChild(int i) {
return (i << 0x01) + 1;
}
private static void swap(int[] arr, int i, int j) {
if (i == j) {
return;
}
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
private static void display(int[] arr) {
for (int i = 0, len = arr.length; i < len; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}