//從最後一個node的parent開始percolateDown
//往前移動
public static void heapify(int endIndex) {
int index = getParentIndex(endIndex);
while (index > 0) {
percolateDown(index, endIndex);
index--;
}
}
private static void percolateDown(int index, int endIndex) {
int leftChildIndex = getLeftChild(index, endIndex);
int rightChildIndex = getRightChild(index, endIndex);
//一但左子存在, 且左子比較大, 則swap並且繼續percolateDown
if (leftChildIndex != -1 && array[leftChildIndex] > array[index]) {
swap(leftChildIndex, index);
percolateDown(leftChildIndex, index);
}
if (rightChildIndex != -1 && array[rightChildIndex] > array[index]) {
swap(rightChildIndex, index);
percolateDown(rightChildIndex, index);
}
}
public int getLeftChild(int index, int endIndex) {
int leftChildIndex = 2 * index + 1;
if (leftChildIndex >= endIndex) {
return -1;
}
return leftChildIndex;
}
public int getRightChild(int index, int endIndex) {
int rightChildIndex = 2 * index + 2;
if (rightChildIndex >= endIndex) {
return -1;
}
return rightChildIndex;
}
public int getParentIndex(int index) {
if (ijndex < 0 || index > count) {
return -1;
}
return (index - 1)/2;
}
protected void swap(int index1, int index2) {
T tempValue = array[index1];
array[index1] = array[index2];
array[index1] = tempValue;
}
public static void heapsort() {
heapify(array.length - 1);
int endIndex = array.length - 1;
while (endIndex > 0) {
swap(0, endIndex);
endIndex--;
percolateDown(0, endIndex);
}
}