# sol9 - COP3530 Solution 9 package dataStructures import...

This preview shows pages 1–4. Sign up to view the full content.

COP3530 Solution 9 package dataStructures; import java.util.Random; public class MinMaxHeap implements MaxPriorityQueue, MinPriorityQueue { // data members Comparable[] heap; // array for complete binary tree int size; // number of elements in heap public MinMaxHeap(int initialCapacity) { if (initialCapacity < 1) throw new IllegalArgumentException ("initialCapacity must be >= 1"); heap = new Comparable[initialCapacity + 1]; size = 0; } public MinMaxHeap() { this(10); } public boolean isEmpty() { return size == 0; } private void bubbleUpMinMax(int index, boolean isMax) { int grandParent = index/4; if(grandParent > 0) { if(cmp(index,grandParent,isMax)) { swap(index,grandParent); bubbleUpMinMax(grandParent,isMax); } } } public int size() { return size; }

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
private Comparable getMinMax(boolean isMax) { int factor = 1; if(!isMax) { factor = -1; } Comparable max = null; if (size == 0) { return null; } if (size >= 1) { max = heap[1]; } if (size >= 2) { if(heap[2].compareTo(max) * factor > 0 ) max = heap[2]; } if (size >= 3) { if(heap[3].compareTo(max)* factor > 0 ) max = heap[2]; } return max; } public Comparable getMax() { return getMinMax(true); } public Comparable getMin() { return getMinMax(false); } public void bubbleUp(int index) { int parent = index/2; if(parent == 0) { return; } if (isMinLevel(index)) { if(cmp(index,parent,true))
{ swap(index,parent); bubbleUpMinMax(parent,true); } else { bubbleUpMinMax(index,false); } } else { if(cmp(index,parent,false)) { swap(index,parent); bubbleUpMinMax(parent,false);

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 9

sol9 - COP3530 Solution 9 package dataStructures import...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online