1. 程式人生 > >二叉堆

二叉堆

delet ava eap else if clas class sys turn right

未經測試:
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;
					}
				}
			}
		}
	}
}

二叉堆