-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinHeap.java
More file actions
95 lines (78 loc) · 1.88 KB
/
MinHeap.java
File metadata and controls
95 lines (78 loc) · 1.88 KB
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
public class MinHeap{
int Heap[];
int size;
int currentSize;
public MinHeap(){
this.size = 10;
this.Heap = new int[this.size];
this.Heap[0] = 0;
currentSize = 0;
}
private int parentpos(int childPos) {
return childPos/2;
}
private int leftChildPos(int parentPos) {
return parentPos * 2;
}
private int rightChildPos(int parentPos) {
return (parentPos * 2) + 1;
}
private boolean isLeaf(int pos) {
if (pos <= currentSize/2) {
return false;
}
return true;
}
private void doubleArray() {
int newSize = 2 * size;
int newArray[] = new int [newSize];
for (int i = 0; i<size; i++) {
newArray[i] = Heap[i];
}
size = newSize;
Heap = newArray;
}
private void swap(int parentPos, int childPos) {
int parent = Heap[parentPos];
Heap[parentPos] = Heap[childPos];
Heap[childPos] = parent;
}
private void swim(int childPos) {
while (Heap[parentpos(childPos)] > Heap[childPos] && childPos > 1) {
swap(parentpos(childPos), childPos);
childPos = parentpos(childPos);
}
}
private void sink(int parentPos) {
while ((Heap[parentPos] > Heap[leftChildPos(parentPos)] || Heap[parentPos] > Heap[rightChildPos(parentPos)]) && isLeaf(parentPos) == false) {
if(Heap[parentPos] > Heap[leftChildPos(parentPos)]) {
swap(parentPos,leftChildPos(parentPos));
parentPos = leftChildPos(parentPos);
}
else if (Heap[parentPos] > Heap[rightChildPos(parentPos)]) {
swap(parentPos,rightChildPos(parentPos));
parentPos = rightChildPos(parentPos);
}
}
}
public void insert(int element) {
if (currentSize + 1 == size) {
doubleArray();
}
Heap[++currentSize] = element;
swim(currentSize);
}
public int getMin() {
return Heap[1];
}
public void delMin() {
swap(1, currentSize);
currentSize --;
sink(1);
}
public void print () {
for (int i = 1; i <= currentSize; i++) {
System.out.println(Heap[i]);
}
}
}