-
Notifications
You must be signed in to change notification settings - Fork 0
/
IntHeap.java
142 lines (115 loc) · 3.09 KB
/
IntHeap.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
/*Whatcom Community College - Winter 2019
CS240 Data Structures and Algorithm Analysis
Professor Ryan Parsons
AUTHORS: Adib Thaqif, Andrew Jacobi, Donald Strong, and Micah Miller
Heap implementation for choosing an event in the rewards feature.
Implemented using an array
*/
import java.io.*;
import java.util.*;
import java.util.Comparator;
public class IntHeap{
private int[] Heap;
private int size = 0;
private int maxSize;
public IntHeap(int maxSize){
this.size = size;
this.maxSize = maxSize;
Heap = new int[maxSize + 1];
}
private int parent(int pos){
return Heap[pos/2];
}
private int leftChild(int pos){
return Heap[2*pos];
}
private int rightChild(int pos){
return Heap[2*pos + 1];
}
private boolean isLeaf(int pos){
return (pos >= (size/2) && pos <= size);
}
private boolean isEmpty(){
return (size == 0);
}
private boolean isFull(){
return (size == Heap.length-1);
}
public String toString(){
// if(isEmpty()){
// throw new IllegalArgumentException();
// }
return Arrays.toString(Heap);
}
private int findMin(){
if(isEmpty()){
throw new IllegalArgumentException("Heap is empty");
}
return Heap[1];
}
private void emptyHeap(){
size = 0;
}
private void resize(){
size++;
}
// public String toString(){
// return
//
// }
public void insert(int value){
if (isFull()){
}
size++;
//System.out.println("size = " + size);
//Heap[size+1] = value;
int i = percolateUp(size,value);
Heap[i] = value;
}
public int deleteMin(){
if(isEmpty()){
throw new IllegalArgumentException();
}
int minItem = Heap[1];
int hole = percolateDown(1,Heap[size]);
Heap[hole] = Heap[size];
size--;
return minItem;
}
private int percolateUp(int hole, int value){
//System.out.println(Heap[hole/2] + "");
while(hole > 1 && (value < Heap[hole/2])){
Heap[hole] = Heap[hole/2];
hole = hole/2;
}
return hole;
//System.out.println(hole);
}
private int percolateDown(int hole, int value){
int target;
while(!isLeaf(hole)){
int left = 2*hole;
int right = left + 1;
if(Heap[left] < Heap[right] || right > size){
target = left;
}else{
target = right;
}
if(Heap[target] < value){
Heap[hole] = Heap[target];
hole = target;
}else{
break;
}
}
return hole;
}
//using Floyd's method to buildHeap
public void buildHeap(){
for (int i = size/2; i > 0; i--){
int value = Heap[i];
int hole = percolateDown(i,value);
Heap[hole] = value;
}
}
}