1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| import java.util.*;
class Program { static class MinHeap { List<Integer> heap = new ArrayList<Integer>();
public MinHeap(List<Integer> array) { heap = buildHeap(array); }
public List<Integer> buildHeap(List<Integer> array) { int firstParent = (array.size() - 2) / 2; for (int i = firstParent; i >= 0; i--) { siftDown(i, array.size() - 1, array); } return array; }
public void siftDown(int currentIdx, int endIdx, List<Integer> heap) { int leftChild = currentIdx * 2 + 1; while (leftChild < heap.size()) { int rightChild = (currentIdx * 2 + 2) < heap.size() ? currentIdx * 2 + 2 : -1; int idxToSwap = leftChild; if (rightChild != -1 && heap.get(leftChild) > heap.get(rightChild)) { idxToSwap = rightChild; } if (heap.get(currentIdx) > heap.get(idxToSwap)) { swap(currentIdx, idxToSwap, heap); currentIdx = idxToSwap; leftChild = currentIdx * 2 + 1; } else { return; } } }
public void siftUp(int currentIdx, List<Integer> heap) { int parentIdx = (currentIdx - 1) / 2; while (parentIdx >= 0) { if (heap.get(currentIdx) < heap.get(parentIdx)) { swap(currentIdx, parentIdx, heap); currentIdx = parentIdx; parentIdx = (currentIdx - 1) / 2; } else { return; } } }
public int peek() { return heap.get(0); }
public int remove() { int valueToRemove = heap.get(0); swap(0, heap.size() - 1, heap); heap.remove(heap.size() - 1); siftDown(0, heap.size() - 1, heap); return valueToRemove; }
public void insert(int value) { this.heap.add(value); siftUp(heap.size() - 1, heap); }
public void swap(int i, int j, List<Integer> array) { int temp = array.get(i); array.set(i, array.get(j)); array.set(j, temp); } } }
|