Vous êtes sur la page 1sur 4

[Mohammed.Shehu.

200900975] Nov 04, 11 13:40

MaxHeap.java

Page 1/7

Nov 04, 11 13:40

MaxHeap.java

Page 2/7

package myutil.adt.elementary; import java.util.*; /** * A MaxHeap class implementing the MaxHeapInterface * @author Mohammed Shehu 200900975 * @version 1.0 */ public class MaxHeap<E extends Comparable<E>> implements Iterable<E> { private static private static s much each time private static private static final int INITIAL_SIZE = 20; //All heaps start out this big final int INCREASING_FACTOR = 10; //...and will increase by thi Comparable[] heap; //Array to hold the elements of the heap int size;

/** * Builds a max heap given an array * @param array the array from which the max heap is to be built * @param the comparator to be used */ public static<E extends Comparable<E>> void buildMaxHeap(E[] array, Comparator cmp){ for(int i = (int)Math.floor(size/2); i >= 1; i){ //Note that we start from 1, meaning that index 0 is empty maxHeapify(array, i, cmp); } }//endmethod //======================================================================

//Constructor public MaxHeap(){ heap = (E[]) new Comparable[INITIAL_SIZE]; //Initialize a a new Comparable A rray size = 0; //Set the size of the heap to zero } //====================================================================== /** * Returns the index of the parent of this index * @param i the index whose parent you want to find * @return the index of index is parent */ public static int parent(int i) { return (i/2); } //====================================================================== /** * Returns the index of this nodes left child * @param i this nodes index * @return the index of this nodes left child */ public static int left(int i){ return (2*i); } //endmethod

/** * Checks if the subtree rooted at i obeys the MaxHeap property * @param i the index of the subtree to MaxHeapify */ public static<E extends Comparable<E>> void maxHeapify(int i){ MaxHeap.maxHeapify(heap, i); }//endmethod

//====================================================================== /** * Checks if the subtree rooted at i obeys the MaxHeap property * @param i the index of the subtree to MaxHeapify * @param cmp the comparator object to be used */ public static<E extends Comparable<E>> void maxHeapify(int i, Comparator cmp){ int left = left(i); //Left child of element i int right = right(i); //Right child of element i int largest; //Will hold the index of the largest element in the subtree if(left <= size && cmp.compare(heap[left], heap[i]) > 0){ largest = left; //The prize goes to the left child } else { largest = i; } //else if the largest was actually at the right childs index if(right <= size && cmp.compare(heap[right], heap[largest]) > 0){ largest = right; //then he takes the grand prize } //wrapping it up if(largest != i){ //if the largest turns out NOT to be i... swap(heap, i, largest); //...swap em out... maxHeapify(heap, largest); //...and maxHeapify where the largest was } }//endmethod

//====================================================================== /** * Returns the index of this nodes right child * @param i this nodes index * @return the index of this nodes right child */ public static int right(int i){ return (2*i + 1); }//endmethod

//====================================================================== /** * Builds a max heap given an array * @param array the array from which the max heap is to be built */ public static<E extends Comparable<E>> void buildMaxHeap(E[] array){ for(int i = (int)Math.floor(size/2); i >= 1; i){ //Note that we start from 1, meaning that index 0 is empty maxHeapify(array, i); } }//endmethod //======================================================================

Friday November 04, 2011

t f e

l t i

M [ e

h o

m a

//====================================================================== /** * Overloaded method that checks if the subtree rooted at i obeys the MaxHea p property * @param array the array of the heap to be worked on * @param i the index of the subtree to MaxHeapify */ public static<E extends Comparable<E>> void maxHeapify(E[] array, int i){ int left = left(i); //Left child of element i int right = right(i); //Roght child of element i int largest; //Will hold the index of the largest element in the subtree if(left <= array.length 1 && array[left].compareTo(array[i]) > 0){ largest = left; //The prize goes to the left child } else { largest = i;

MaxHeap.java

1/4

[Mohammed.Shehu.200900975] Nov 04, 11 13:40

MaxHeap.java

Page 3/7

Nov 04, 11 13:40


}

MaxHeap.java

Page 4/7

} //else if the largest was actually at the right childs index if(right <= array.length 1 && array[right].compareTo(array[largest]) > 0){ largest = right; //then he takes the grand prize } //wrapping it up if(largest != i){ //if the largest turns out NOT to be i... swap((E[])array,i, largest); //...swap em out... maxHeapify(array, largest); //...and maxHeapify where the largest was } }//endmethod //====================================================================== /** * Overloaded method that checks if the subtree rooted at i obeys the MaxHea p property * @param array the array of the heap to be worked on * @param i the index of the subtree to MaxHeapify */ public static<E extends Comparable<E>> void maxHeapify(E[] array, int i, Compa rator cmp){ int left = left(i); //Left child of element i int right = right(i); //Roght child of element i int largest; //Will hold the index of the largest element in the subtree if(left <= array.length 1 && (cmp.compare(array[left], array[i]) > 0)){ largest = left; //The prize goes to the left child } else { largest = i; } //else if the largest was actually at the right childs index if(right <= array.length 1 && (cmp.compare(array[right], array[largest])) > 0){ largest = right; //then he takes the grand prize } //wrapping it up if(largest != i){ //if the largest turns out NOT to be i... swap((E[])array, i, largest); //...swap em out... maxHeapify(array, largest); //...and maxHeapify where the largest was } }//endmethod //====================================================================== /** * Checks if the heap is empty * @return true of there are no elements in the heap; false otherwise */ public static boolean isEmpty(){ return size == 0; }//endmethod

heap = newHeap; //Update the heap attribute } //On the other hand... if (size == 0) { //...if theres nothing in the heap... heap[size] = element; //Insert the new element at the end... size++; //...and update the size }

//Normal case else { int i = size; heap[size] = element; //Insert the element at the bottom of the heap .

//While the element at i is greater than the element at its parent index.. while (i > 1 && (heap[parent(i)].compareTo(element) < 0)){ //swap em out... swap(heap, i, parent(i)); i = parent(i); //Keep moving up the heap and checking } size++; } }//endmethod

//====================================================================== /** * Insert an element into the heap * @param element the element to be inserted into the heap */ public static<E extends Comparable<E>> void insert(E element) { if(size == INITIAL_SIZE) { //If weve reached the limit... //Calculate a new length int newLength = heap.length + INCREASING_FACTOR; //Create a new Comparable array of that new length Comparable[] newHeap = (E[]) new Comparable[newLength]; for(int i = 1; i < heap.length; i++){ //Proceed to populate the new heap with the contents of the old heap newHeap[i] = heap[i];

Friday November 04, 2011

t f e

l t i

M [ e

//====================================================================== /** * Removes the maximum element in the heap and returns its data value * @return the data value in the maximum element in the heap */ public static<E extends Comparable<E>> E extractMaximum() { if (size < 1) { //i.e. no elements in the heap throw new UnderflowException("No elements in heap"); } E max = (E)heap[1]; //Store the largest elements data in max heap[1] = heap[size]; //Move smallest element to index of largest element size = size 1; //Reduce the heap size heap = truncate(heap, 1); //Truncate the heap array to that new size maxHeapify(heap, 1); //Min heapify return max; //Return the minimum }//end "extractMaximum"

h o

m a

//====================================================================== /** * Returns the maximum element without altering anything * @return the maximum element */ public E maximum() { Comparable max = null; if(!isEmpty()){ max = heap[0]; } return (E)max; }//end "maximum" //====================================================================== /** * Reduces an array by the specified size * @param array the array to be truncated * @param factor the number of cells by which the array should be reduced * @return the newly truncated array * @throws IndexOutOfBoundsException */

MaxHeap.java

2/4

[Mohammed.Shehu.200900975] Nov 04, 11 13:40

MaxHeap.java

Page 5/7

Nov 04, 11 13:40

MaxHeap.java

Page 6/7

public static<E extends Comparable<E>> E[] truncate(E[] array, int factor) thr ows IndexOutOfBoundsException { if (factor >= array.length 1) { //Throw an exception because then youll be... //...getting rid of array altogether throw new IndexOutOfBoundsException("Truncate factor "+factor+ " is greater than array length " + array.length) ; } //If factor is fine, proceed as usual Comparable[] result = (E[]) new Comparable[array.length factor]; //Create a truncated array //Populate it for (int i = 0; i < result.length; i++) { //Fill up to the length of the res ultant array result[i] = array[i]; } return (E[]) result; //Return the resulting array cast as a type E object array }//endmethod //====================================================================== /** * Sorts a heap * @param array the array of the heap to be sorted */ public static<E extends Comparable<E>> void heapsort(E[] array) { buildMaxHeap(array); for (int i = array.length 1; i >= 2; i) { swap(array, 1, i); maxHeapify(array, 1); //Min heapify from the root } } //======================================================================

/** * Returns the element at a specified index * @param index the specified index * @return the data in that index */ public static<E extends Comparable<E>> E get(int index) { return (index > size)? null : (E)heap[index]; }//endmethod

//====================================================================== /** * Returns an iterator of this instance * @return an Iterator object of this instance */ public Iterator<E> iterator() { return new MaxHeapIterator(); }//endmethod "iterator"

//====================================================================== /** * Iterator class * Returns values in no paricular order * @author Mohammed Shehu 200900975 * @version 1.0 */ private class MaxHeapIterator implements Iterator<E> { private int current; // List index currently pointed to public MaxHeapIterator() { current = 0; //Point to the first element in the heap }

/** * Simple method to swap out the contents of 2 indices * @param ray the array where the swapping will take place * @param i the first index * @param j the second index */ public static<E extends Comparable<E>> void swap(E[] array, int i, int j) { E temp = array[i]; array[i] = array[j]; array[j] = temp; }//endmethod //====================================================================== /**Returns the heap in array form * @return the array representation of this heap */ public static<E extends Comparable<E>> E[] toArray() { return (E[])heap; //Return this heap in array form }//endmethod

//====================================================================== /** * Returns the size of the MaxHeap * @return the size of the max heap */ public static<E extends Comparable<E>> int size() { return size; } //======================================================================

Friday November 04, 2011

t f e

l t i

M [ e
return value; }//endmethod "next"

h o

m a

/** * Check if the list has any more elements * @return true if current is not at the end; false otherwise */ public boolean hasNext() { return current <= size; }//endmethod "hasNext"

/** * Gets the next element in the heap * @return the next element in the heap * @throws NoSuchElementException */ public E next() throws NoSuchElementException { if (!hasNext()) throw new NoSuchElementException("No more elements!"); E value = (E)heap[current]; current += 1;

/** * An attempt to remove an element from the list * Throws an exception * @throws UnsupportedOperationException */ public void remove() { throw new UnsupportedOperationException("Operation not allowed"); }//endmethod "remove" } //ENDCLASS "MinPQIterator"

MaxHeap.java

3/4

[Mohammed.Shehu.200900975] Nov 04, 11 13:40


} //====================================================================== /** * General allpurpose Exception class for access in empty ADTs * such as stacks, queues, and priority queues. * @author Mohammed Shehu 200900975 */ class UnderflowException extends RuntimeException { /** * Construct this exception object. * @param message the error message. */ public UnderflowException(String message) { //Takes a message super(message); //Throws the exception together with the specified message } }

MaxHeap.java

Page 7/7

Friday November 04, 2011

t f e

l t i

M [ e

h o

m a

MaxHeap.java

4/4

Vous aimerez peut-être aussi