public class Heap{
private int[] heap;
int N = 0;
public Heap(int maxN) {
heap = new int[maxN + 1]; //first element isn't used
}
public void insert(int i) {
heap[++N] = i;
swim(N);
}
public int max() {
int v = heap[1];
exch(1, N--);
heap[N + 1] = null;
sink(1);
return v;
}
private swim(int i) {
while(i > 1 && heap[i/2] < heap[i]) {
exch(i/2, i);
i = i/2;
}
}
private sink(int i) {
while(i * 2 <= N) {
int j = i * 2;
if(j < N && heap[j] < heap[j + 1]) j ++;
if(heap[i] > heap[j]) break;
exch(i, j);
i = j;
}
}
private exch(int i, int j) {int v = heap[i]; heap[i] = heap[j]; heap[j] = v;}
}
private int[] heap;
int N = 0;
public Heap(int maxN) {
heap = new int[maxN + 1]; //first element isn't used
}
public void insert(int i) {
heap[++N] = i;
swim(N);
}
public int max() {
int v = heap[1];
exch(1, N--);
heap[N + 1] = null;
sink(1);
return v;
}
private swim(int i) {
while(i > 1 && heap[i/2] < heap[i]) {
exch(i/2, i);
i = i/2;
}
}
private sink(int i) {
while(i * 2 <= N) {
int j = i * 2;
if(j < N && heap[j] < heap[j + 1]) j ++;
if(heap[i] > heap[j]) break;
exch(i, j);
i = j;
}
}
private exch(int i, int j) {int v = heap[i]; heap[i] = heap[j]; heap[j] = v;}
}