这里的堆是堆数据结构,而不是java中的垃圾收集存储。
堆(二叉堆)是一个数组,可以被看成一个近似的完全二叉树。
二叉堆可以分为2种形式:最大堆、最小堆
- 最大堆
A[parent(i)] >= A[i]
- 最小堆
A[parent(i)] <= A[i]
public int heapSize = 7;
public Integer[] a = new Integer[]{10, 7, 19, 3, 6, 46, 44, 45};
// 下标 1,2, 3, 4,5, 6, 7, 8
public void heapSort() {
buildMaxHeap(a);
System.out.println(Arrays.asList(a));
for (int i = a.length; i >= 2; i--) {
// exchange A[1] with A[i]
Integer key = a[i - 1];
a[i - 1] = a[0];
a[0] = key;
this.heapSize = this.heapSize - 1;
maxHeapIfy(1);
}
}
public void buildMaxHeap(Integer[] A) {
heapSize = a.length;
for (int i = A.length / 2; i > 0; i--) {
maxHeapIfy(i);
}
}
public void maxHeapIfy(int i) {
// 查找左右子节点
Integer leftIndex = left(i);
Integer rightIndex = right(i);
// 最大节点
Integer largest;
if (leftIndex <= a.length - 1 && a[leftIndex - 1] > a[i - 1]) {
largest = leftIndex;
} else {
largest = i;
}
if (rightIndex <= a.length - 1 && a[rightIndex - 1] > a[largest - 1]) {
largest = rightIndex;
}
if (largest != i) {
// exchange A[i] with A[largest]
Integer key = a[i - 1];
a[i - 1] = a[largest - 1];
a[largest - 1] = key;
maxHeapIfy(largest);
}
}
public int left(int i) {
return 2 * i;
}
public int right(int i) {
return 2 * i + 1;
}
public int parent(int i) {
return i / 2;
}