-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinHeap.java
106 lines (89 loc) · 2.31 KB
/
MinHeap.java
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package com.adolfoeloy.datastructure.heap;
import java.util.Arrays;
public class MinHeap implements IntHeap {
private int size;
private final int[] heap;
public MinHeap(int maxSize) {
heap = new int[maxSize + 1];
}
public MinHeap(int[] input) {
heap = new int[input.length + 1];
Arrays.stream(input).forEach(this::add);
}
@Override
public void add(int value) {
if (size + 1 == heap.length) {
throw new IllegalStateException("Cannot add more than heap max size");
}
size++;
int index = size;
heap[index] = value;
swim(index);
}
@Override
public int poll() {
if (size == 0) {
throw new IllegalStateException("Heap is empty");
}
var min = heap[1];
heap[1] = heap[size];
heap[size] = 0;
size--;
var index = 1;
sink(index);
return min;
}
@Override
public int peek() {
if (size == 0) {
throw new IllegalStateException("Heap is empty");
}
return heap[1];
}
private void swim(int index) {
while (index > 0) {
var parent = index / 2;
if (heap[index] < heap[parent]) {
swap(index, parent);
index = parent;
} else {
break;
}
}
}
private void sink(int index) {
while (index <= size / 2) {
var left = index * 2;
var right = index * 2 + 1;
if (right < size) {
var minIndex = minIndexBetween(left, right);
swap(index, minIndex);
index = minIndex;
} else {
if (heap[index] > heap[left]) {
swap(index, left);
}
index = left;
}
}
}
int minIndexBetween(int i, int j) {
if (heap[i] <= heap[j]) {
return i;
}
return j;
}
private void swap(int index, int parent) {
var tmp = heap[index];
heap[index] = heap[parent];
heap[parent] = tmp;
}
@Override
public int size() {
return size;
}
@Override
public int[] asArray() {
return Arrays.copyOfRange(heap, 1, size + 1);
}
}