// PQueueInt.java: priority queue of integers
public class PQueueInt {
private int[] A;
private int heapsize;
public PQueueInt(int[] Ap, int hs) {
A = Ap;
heapsize = hs;
}
public int qSize() { return heapsize; }
public int heapMaximum() {
if (heapsize < 1) {
System.out.println("Empty Queue");
System.exit(0);
}
return A[1];
}
public int heapExtractMax() {
if (heapsize < 1) {
System.out.println("Heap Underflow");
System.exit(0);
}
int max = A[1];
A[1] = A[heapsize];
heapsize--;
maxHeapify(1);
return max;
}
private int parent(int i) {return i/2;}
private int left (int i) {return 2*i;}
private int right (int i) {return 2*i + 1;}
private void exchange(int i, int largest) {
int temp = A[i];
A[i] = A[largest];
A[largest] = temp;
}
private void maxHeapify(int i) {
printheap("maxHeapify");
int l = left(i);
int r = right(i);
int largest;
if (l <= heapsize && A[l] > A[i])
largest = l;
else largest = i;
if (r <= heapsize && A[r] > A[largest])
largest = r;
if (largest != i) {
exchange(i, largest);
maxHeapify(largest);
}
}
| public void maxHeapInsert(int key) {
if (heapsize >= A.length - 1) {
System.out.println("Heap Overflow");
System.exit(1);
}
printheap("maxHeapInsert");
heapsize++;
A[heapsize] = -2000000000;
heapIncreaseKey(heapsize, key);
}
void heapIncreaseKey(int i, int key) {
if (key < A[i]) {
System.out.println("New key < Current");
System.exit(2);
}
printheap("heapIncreaseKey");
A[i] = key;
printheap("heapIncreaseKey");
while (i > 1 && A[parent(i)] < A[i]) {
exchange(i, parent(i));
i = parent(i);
printheap("heapIncreaseKey");
}
}
public void printheap(String id) {
System.out.print(id + ": heapsize:" +
heapsize + ", heap: ");
for (int i = 1; i <= heapsize; i++) {
System.out.print(A[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] A =
{0,15,13,9,5,12,8,7,4,0,6,2,1,-1,-1,-1};
int heapsize = 12;
PQueueInt pq = new PQueueInt(A, heapsize);
pq.printheap("main");
// do one of the other of the two below:
System.out.println("Max of heap: " +
pq.heapExtractMax()); // Problem 2
// pq.maxHeapInsert(10); // Problem 3
pq.printheap("main");
}
}
|