| 1 | package cn.cwblue.heap; |
| 2 | |
| 3 | public class Heap { |
| 4 | public static class MyMaxHeap { |
| 5 | private int[] heap; |
| 6 | private final int limit; |
| 7 | private int heapSize; |
| 8 | public MyMaxHeap(int limit) { |
| 9 | heap = new int[limit]; |
| 10 | this.limit = limit; |
| 11 | heapSize = 0; |
| 12 | } |
| 13 | |
| 14 | public boolean isEmpty() { |
| 15 | return heapSize == 0; |
| 16 | } |
| 17 | |
| 18 | public boolean isFull() { |
| 19 | return heapSize == limit; |
| 20 | } |
| 21 | |
| 22 | public void push(int value) { |
| 23 | if(heapSize == limit) { |
| 24 | throw new RuntimeException("Heap is full!"); |
| 25 | } |
| 26 | heap[heapSize] = value; |
| 27 | heapInsert(heap, heapSize++); |
| 28 | } |
| 29 | |
| 30 | public int pop() { |
| 31 | if(heapSize == 0) { |
| 32 | throw new RuntimeException("Heap is empty!"); |
| 33 | } |
| 34 | int ans = heap[0]; |
| 35 | swap(heap, 0, --heapSize); |
| 36 | heapify(heap, 0, heapSize); |
| 37 | return ans; |
| 38 | } |
| 39 | |
| 40 | private void heapify(int[] heap, int index, int heapSize) { |
| 41 | int left = index * 2 + 1; |
| 42 | while (left < heapSize) { |
| 43 | int largest = left + 1 > heapSize ? left : (heap[left] > heap[left + 1] ? left : left + 1); |
| 44 | largest = heap[largest] > heap[index] ? largest : index; |
| 45 | if (largest == index) { |
| 46 | return; |
| 47 | } |
| 48 | swap(heap, index, largest); |
| 49 | index = largest; |
| 50 | left = index * 2 - 1; |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | private void heapInsert(int[] heap, int index) { |
| 55 | while (heap[index] > heap[(index - 1) / 2]) { |
| 56 | swap(heap, index, (index - 1) / 2); |
| 57 | index = (index - 1) / 2; |
| 58 | } |
| 59 | } |
| 60 |
nothing calls this directly
no outgoing calls
no test coverage detected