public class TestHeap<T extends Comparable> { Object[] data; /** * 初始容量 */ int initCapacity = 8; /** * 加载因子 */ float factor = 0.75f; /** * 长度 */ int size = 0; public TestHeap (){ data = new Object[initCapacity]; } public void add(T obj){ reset(); data[size] = obj; size++; swim(size); } private void reset(){ float f = (float)size/data.length; if(f > factor){ Object[] temp = new Object[data.length<<1]; System.arraycopy(data,0,temp,0,data.length); data = temp; } } public T pop(){ if(size < 1){ return null; } Object d = data[0]; data[0] = data[--size]; data[size] = null; subside(0); return (T)d; } /** * 下沉 * @param index 坐标 */ private void subside(int index){ int leftChildIndex = index == 0 ? 1: (index +1)*2 -1; int rightChildIndex = index == 0 ?2: (index +1)*2; if(leftChildIndex >= size && rightChildIndex >= size){ return; } if(leftChildIndex < size &&((T)data[index]).compareTo(data[leftChildIndex]) < 0 ){ if(rightChildIndex < size &&((T)data[index]).compareTo(data[rightChildIndex]) < 0){ if(((T)data[leftChildIndex]).compareTo(data[rightChildIndex]) < 0){ swap(index,rightChildIndex); subside(rightChildIndex); }else{ swap(index,leftChildIndex); subside(leftChildIndex); } }else{ swap(index,leftChildIndex); subside(leftChildIndex); } }else if(rightChildIndex < size && ((T)data[index]).compareTo(data[rightChildIndex]) < 0 ){ swap(index,rightChildIndex); subside(rightChildIndex); } } /** * 跟父节点比较<br> * @param index 节点的坐标 */ private void swim(int index){ while(index > 1 && ((T)data[index-1]).compareTo(data[index/2 -1]) > 0){ swap(index/2 -1,index-1); index = index/2; } } /** * 交换位置<br> * @param preIndex * @param afterIndex */ private void swap(int preIndex,int afterIndex){ Object temp = data[preIndex]; data[preIndex] = data[afterIndex]; data[afterIndex] = temp; } public static void main(String[] args) { TestHeap heap = new TestHeap(); for (int i =0;i<100;i++){ heap.add(Integer.valueOf(""+i)); } Object tmp = null; while((tmp = heap.pop()) != null){ System.out.println("=="+tmp); } } }
转载于:https://my.oschina.net/u/2504004/blog/3020485