-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMaxHeap.java
53 lines (45 loc) · 1.35 KB
/
MaxHeap.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
package datastructure.heap;
public class MaxHeap implements Heap {
private int[] items = null;
private int size;
private int capacity = 10;
public MaxHeap() {
items = new int[capacity];
}
public void insert(int item) {
items = HeapUtility.ensureExtraCapacity(items, size, capacity);
if (size == capacity)
capacity *= 2;
items[size++] = item;
heapifyUp();
}
public void heapifyUp() {
int index = size - 1;
while (HeapUtility.hasParent(index) && HeapUtility.parent(index, items) < items[index]) {
HeapUtility.swap(HeapUtility.getParentIndex(index), index, items);
index = HeapUtility.getParentIndex(index);
}
}
public void heapifyDown() {
int index = 0;
while (HeapUtility.hasLeftChild(index, size)) {
int biggerChildIndex = HeapUtility.getLeftChildIndex(index);
if (HeapUtility.hasRightChild(index, size)
&& HeapUtility.rightChild(index, items) > HeapUtility.leftChild(index, items))
biggerChildIndex = HeapUtility.getRightChildIndex(index);
if (items[index] > items[biggerChildIndex])
break;
else
HeapUtility.swap(index, biggerChildIndex, items);
index = biggerChildIndex;
}
}
@Override
public int pop() {
int item = items[0];
items[0] = items[size - 1];
size--;
heapifyDown();
return item;
}
}