-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMaxHeap.java
134 lines (107 loc) · 2.74 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
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package DSImplementations;
import java.util.Arrays;
public class MaxHeap<T extends Comparable<T>> {
private int capacity;
private int size;
private T[] heap;
@SuppressWarnings("unchecked")
public MaxHeap() {
this.size = 0;
this.capacity = 10;
this.heap = (T[]) new Comparable<?>[capacity];
}
public void insert(T data) {
ensureCapacity();
heap[size] = data;
// heapifyUp();
int current = size;
while (heap[current].compareTo(heap[getParentIndex(current)]) > 0) {
swap(current, getParentIndex(current));
current = getParentIndex(current);
}
size++;
}
public T peek() {
if (size == 0) {
throw new IllegalStateException("Heap is empty");
}
return heap[0];
}
public T poll() {
if (size == 0) {
throw new IllegalStateException("Heap is empty");
}
T popped = heap[0];
heap[0] = heap[size - 1];
size--;
maxHeapify(0);
return popped;
}
public T search(T target) {
for (int i = 0; i < size; i++) {
if (heap[i].equals(target)) {
return heap[i];
}
}
return null;
}
private void maxHeapify(int index) {
if (isLeaf(index)) {
return;
}
int left = getLeftChildIndex(index);
int right = getRightChildIndex(index);
int largest = index;
if (left < size && heap[left].compareTo(heap[largest]) > 0) {
largest = left;
}
if (right < size && heap[right].compareTo(heap[largest]) > 0) {
largest = right;
}
if (largest != index) {
swap(index, largest);
maxHeapify(largest);
}
}
public void print() {
for (int i = 0; i < size; i++) {
System.out.print(heap[i] + ", ");
}
System.out.println();
}
private void swap(int firstIndex, int secondIndex) {
T temp = heap[firstIndex];
heap[firstIndex] = heap[secondIndex];
heap[secondIndex] = temp;
}
private void ensureCapacity() {
if (size == capacity) {
heap = Arrays.copyOf(heap, capacity * 2);
capacity *= 2;
}
}
private boolean isLeaf(int index) {
return index >= (size / 2) && index <= size;
}
private int getParentIndex(int childIndex) {
return (childIndex - 1) / 2;
}
private int getLeftChildIndex(int parentIndex) {
return 2 * parentIndex + 1;
}
private int getRightChildIndex(int parentIndex) {
return 2 * parentIndex + 2;
}
public T[] getHeap() {
return heap;
}
public void setHeap(T[] heap) {
this.heap = heap;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}