-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAscendingHeap.java
More file actions
85 lines (69 loc) · 1.79 KB
/
AscendingHeap.java
File metadata and controls
85 lines (69 loc) · 1.79 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
package heap;
import java.util.Arrays;
public class AscendingHeap {
private Integer[] heapData;
private int currentPosition = -1;
public AscendingHeap(int size) {
this.heapData = new Integer[size];
}
public void insert(int item) {
if (isFull())
throw new RuntimeException("Heap is full");
this.heapData[++currentPosition] = item;
fixUp(currentPosition);
}
public int deleteRoot() {
int result = heapData[0];
heapData[0] = heapData[currentPosition--];
heapData[currentPosition+1] = null;
fixDown(0);
return result;
}
private void fixDown(int index) {
while (index <= currentPosition) {
int leftChild = 2 * index + 1;
int rightChild = 2 * index + 2;
if (leftChild <= currentPosition) {
int childToSwap;
if (rightChild > currentPosition)
childToSwap = leftChild;
else
childToSwap = (heapData[leftChild] < heapData[rightChild]) ? leftChild : rightChild;
if (heapData[index] > heapData[childToSwap]) {
int tmp = heapData[index];
heapData[index] = heapData[childToSwap];
heapData[childToSwap] = tmp;
} else {
break;
}
index = childToSwap;
} else {
break;
}
}
}
private void fixUp(int index) {
int i = (index-1)/2; //parent index
while (i >= 0 && heapData[i] > heapData[index]) {
int tmp = heapData[i];
heapData[i] = heapData[index];
heapData[index] = tmp;
index = i;
i = (index-1)/2;
}
}
private boolean isFull() {
return currentPosition == heapData.length-1;
}
public static void main(String[] args) {
AscendingHeap heap = new AscendingHeap(10);
heap.insert(10);
heap.insert(15);
heap.insert(27);
heap.insert(5);
heap.insert(2);
heap.insert(21);
System.out.println(heap.deleteRoot());
System.out.println(Arrays.deepToString(heap.heapData));
}
}