-
Notifications
You must be signed in to change notification settings - Fork 17
/
MaxHeap.java
96 lines (79 loc) · 1.92 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
package heap;
public class MaxHeap {
private int Heap[];
private int maxsize;
private int size;
private static int FRONT = 1;
public MaxHeap(int maxsize) {
this.maxsize = maxsize;
this.size = 0;
Heap = new int [maxsize+1];
Heap[0] = Integer.MAX_VALUE;
}
private int parent(int pos) {
return pos/2;
}
private int leftChild(int pos) {
return 2*pos;
}
private int rightChild(int pos) {
return (2*pos) + 1;
}
private void swap(int a, int b) {
int temp = Heap[a];
Heap[a] = Heap[b];
Heap[b] = temp;
}
private boolean isLeaf(int pos) {
if(pos > (size/2) && pos <= size) {
return true;
}
return false;
}
public void insert(int element) {
if(size >= maxsize) {
System.out.println("maxsize is reached");
return;
}
Heap[++size] = element;
int current = size;
while(Heap[current] > Heap[parent(current)]) {
swap(current, parent(current));
current = parent(current);
}
}
private void maxHeapify(int pos) {
if(!isLeaf(pos)) {
if(Heap[pos] < Heap[leftChild(pos)] ||
Heap[pos] < Heap[rightChild(pos)]) {
if(Heap[leftChild(pos)] > Heap[rightChild(pos)]) {
swap(pos, leftChild(pos));
maxHeapify(leftChild(pos));
} else {
swap(pos, rightChild(pos));
maxHeapify(rightChild(pos));
}
}
}
}
public void print() {
for(int i = 1; i <= size/2; i++) {
if(2*i + 1 > size) {
System.out.print(" PARENT : " + Heap[i]
+ " LEFT CHILD : " + Heap[2 * i]
+ " RIGHT CHILD : null");
} else {
System.out.print(" PARENT : " + Heap[i]
+ " LEFT CHILD : " + Heap[2 * i]
+ " RIGHT CHILD :" + Heap[2 * i + 1]);
}
System.out.println();
}
}
public int remove() {
int popped = Heap[FRONT];
Heap[FRONT] = Heap[size--];
maxHeapify(FRONT);
return popped;
}
}