未经測试:
public class BinaryHeap {
public static final int INIT_CAPACITY = 10;
private int[] mArray;
private int mLength;
public BinaryHeap() {
mArray = new int[INIT_CAPACITY + 1];
mLength = 0;
}
private void expandArray(int length) {
int[] arr = new int[length];
System.arraycopy(mArray, 1, arr, 1, mLength);
mArray = arr;
}
public static final int[] buildHeap(int arr[], int length) {
if (null == arr || length >= arr.length) {
return null;
}
int[] ret = new int[length + 1];
System.arraycopy(arr, 0, ret, 1, length);
// 把第i个value沉下去:
for (int i = length / 2; i > 0; i--) {
int index = i;
while (true) {
int leftIndex = 2 * index;
int rightIndex = leftIndex + 1;
int value = ret[index];
if (leftIndex > length) { // 出界了
break;
} else if (rightIndex > length) { // 左边没有出界
if (value > ret[leftIndex]) {
ret[index] = ret[leftIndex];
ret[leftIndex] = value;
}
break;
} else { // 两个都没有出界
int lv = ret[leftIndex];
int rv = ret[rightIndex];
if (value <= lv && value <= rv) {
break;
} else if (lv < rv) {
ret[index] = ret[lv];
ret[lv] = value;
index = lv;
} else {
ret[index] = ret[rv];
ret[rv] = value;
index = rv;
}
}
}
}
return ret;
}
public void insert(int value) {
if (mLength >= mArray.length - 1) {
expandArray(mArray.length * 2);
}
mArray[++mLength] = value;
int index = mLength;
int parentIndex = index / 2;
while (parentIndex > 0) {
int currentValue = mArray[index];
int parentValue = mArray[parentIndex];
if (currentValue < parentValue) {
mArray[parentIndex] = currentValue;
mArray[index] = parentValue;
index = parentIndex;
parentIndex /= 2;
} else {
break;
}
}
}
public void deleteMin() {
if (mLength <= 0) {
return;
} else if (mLength == 1) {
mLength--;
} else {
mArray[1] = mArray[mLength];
int index = 1;
mLength--;
while (true) {
int leftIndex = index * 2;
int rightIndex = leftIndex + 1;
int value = mArray[index];
if (leftIndex > mLength) { // 两个都出界了
break;
} else if (rightIndex > mLength) { // 仅仅有右边的出界了
int leftValue = mArray[leftIndex];
if (value > leftValue) { // 换换
mArray[index] = leftValue;
mArray[leftIndex] = value;
}
break;
} else { // 两个都没有出界,须要循环
int leftValue = mArray[leftIndex];
int rightValue = mArray[rightIndex];
if (value <= leftValue && value <=rightValue) { // 好了
break;
} else if (leftValue < rightValue) { // 意味着:value > leftValue
mArray[index] = leftValue;
mArray[leftIndex] = value;
index = leftIndex;
} else { // rightValue >= leftValue , 意味着:value > rightValue
mArray[index] = rightValue;
mArray[rightIndex] = value;
index = rightIndex;
}
}
}
}
}
}