-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeap.java
More file actions
99 lines (77 loc) · 1.86 KB
/
Heap.java
File metadata and controls
99 lines (77 loc) · 1.86 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
96
97
98
99
public class Heap {
Node[] my_heap;
int count = 0;
public boolean isEmpty() {
return (count == 0);
}
public void add(Node value) {
if(count == my_heap.length - 1) resize();
count++;
my_heap[count] = value;
siftUp(count);
}
public int size() {
return count;
}
private void resize() {
Node[] temp = new Node[count * 2 + 1];
for(int i = 1; i <= count; i++) {
temp[i] = my_heap[i];
}
my_heap = temp;
}
public void siftUp(int pos) {
// System.out.println("THIS IS POS" + pos);
if(pos > 1 && my_heap[pos].compareTo(my_heap[pos/2]) < 0) {
swap(pos, pos/2);
siftUp(pos/2);
}
}
public Node remove() {
if(count == 0) return null;
Node temp = my_heap[1];
my_heap[1] = my_heap[count];
count--;
siftDown(1);
return temp;
}
public void siftDown(int pos) {
if(2 * pos > count) return;
if(2 * pos == count) {
if(my_heap[2 * pos].compareTo(my_heap[pos]) < 0) {
swap(pos, 2 * pos);
}
}
else {
int smaller;
if(my_heap[2 * pos].compareTo(my_heap[2 * pos + 1]) <= 0) smaller = 2 * pos;
else smaller = 2 * pos + 1;
if(my_heap[pos].compareTo(my_heap[smaller]) > 0) {
swap(pos, smaller);
siftDown(smaller);
}
}
}
public void swap(int i, int j) {
Node temp = my_heap[i];
my_heap[i] = my_heap[j];
my_heap[j] = temp;
}
public void print() {
for(int i = 1; i <= count; i++) {
System.out.println(my_heap[i]);
}
}
public Heap() {
my_heap = new Node[2];
}
public void decreaseKey(Node node, int shorterDistance) {
int toSift = 1;
for(int i =0; i < my_heap.length; i++) {
if(my_heap[i] != null && my_heap[i].index == node.index ) {
toSift = i;
}
}
siftUp(toSift);
}
}