/** * Created by lin on 2018/9/13. */ public class Heap { private int length; int size = 0; private Integer[] queue; //初始化堆 public Heap(int length) { this.queue = new Integer[length + 1]; } //添加元素,每次添加到堆末尾,需要重新向上调整调整 public void add(int k) {
if (size >= length) { throw new RuntimeException("容量溢出"); } queue[++size] = k; fixUp(size); } //向上调整 public void fixUp(int k) { while (k > 1) { int j = k >> 1; if (queue[j] < queue[k]) { break; } int tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp; k = j; } } //移除堆顶元素,移除后将堆尾元素补置堆顶重新并重新向下调整 public Integer removeMin() { Integer target = queue[1]; queue[1] = queue[size]; queue[size--] = null; fixDown(1); return target; } //向下调整 public void fixDown(int k) { int j = k << 1; while (j <= size && j > 0) { if (j + 1 <= size && queue[j + 1] < queue[j]) { j++; } if (queue[j] < queue[k]) { int temp = queue[j]; queue[j] = queue[k]; queue[k] = temp; k = j; continue; } break; } } }