Datasets:
ArXiv:
License:
File size: 2,390 Bytes
c574d3a |
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 |
package rd222dv_assign4.binheap;
public class BinaryIntHeap {
// Important from lecture notes:
// An array can be used to store the elements in a binary heap + Position 0
// is never used
// The root node is always in position 1 //Elements are added layer by layer
private int[] heap;
private int size;
public BinaryIntHeap() { // Constructs an empty heap
heap = new int[8];
size = 1;
}
public void insert(int n) { // Add n to heap
if (size == 1) {
heap[size] = n;
size++;
} else if (size > 1) {
if (size == heap.length) // resize
resize();
heap[size++] = n;
}
int index = size - 1;
check(index);
}
public int pullHighest() { // Return and remove element with highest
// priority
if (size == 1) {
throw new IllegalArgumentException("Queue is Empty");
}
int temp = heap[1]; //picking the first element and saving it in a variable
heap[1] = heap[size - 1]; //decrease
size--;
int index = 1;
swap(index);
return temp;
}
public int size() { // Current heap size
return size - 1;
}
public boolean isEmpty() { // True if heap is empty
return size == 1;
}
private void check(int a) {
if (a == 1) { //if index is 1, return
return;
} else if (heap[a] <= heap[a / 2]) //return if smaller than the parent
return;
else {
int pos = a; //if both false, do recursion until root is reached
int temp = heap[a / 2];
int index = a / 2;
heap[index] = heap[a];
heap[pos] = temp;
check(index);
}
}
private void resize() { //double the size of the array
int[] temp = new int[heap.length * 2];
for (int i = 0; i < size; i++) {
temp[i] = heap[i];
}
heap = temp;
}
private void swap(int n) {
if (n == size - 1 || n * 2 > size - 1 || n * 2 + 1 > size - 1) { //return if last or no children
return;
}
int left = heap[n * 2];
int right = heap[n * 2 + 1];
if (heap[n] >= left && heap[n] >= right) { //check if element at parameter index is >= to children, if so-return
return;
} else {
if (left >= right) { //checking which child is bigger and then swap
int temp = heap[n];
heap[n] = left;
heap[n * 2] = temp;
swap(n * 2);
} else {
int temp = heap[n];
heap[n] = right;
heap[n * 2 + 1] = temp;
swap(n * 2 + 1);
}
}
}
}
|