heaps. 2 a complete binary tree nodes contain comparable objects each node contains no smaller (or...
TRANSCRIPT
2
HeapsA complete binary tree• Nodes contain Comparable objects• Each node contains no smaller (or no larger) than
objects in its descendants
Maxheap• Object in a node is ≥ its descendant objects
Minheap• Object in a node is ≤ descendant objects
Note contrast of uses of the word "heap"• The ADT heap• The heap from which memory is allocated (by the OS)
when new executes
3
Heaps
(a) maxheap and (b) minheap containing the same values
Consider how to use a heap to implement a priority queue…
4
The ADT Heap
Interface used for implementation of maxheap
public interface MaxHeapInterface {public void add(Comparable newEntry);public Comparable removeMax();public Comparable getMax();public boolean isEmpty();public int getSize();public void clear();
} // end MaxHeapInterface
5
Using an Array to Represent a Heap
(a) A complete binary tree with its nodes numbered in level order; (b) its representation as an array.
6
Using an Array to Represent a Heap
When a binary tree is complete• Can use level-order traversal to store data in
consecutive locations of an array
Enables easy location of the data in a node's parent or children• Parent of a node at i is found at i/2
(unless i is 1)• Children of node at i found at indices
2i and 2i + 1
7
public class MaxHeap implements MaxHeapInterface, java.io.Serializable {private Comparable[ ] heap; // array of heap entriesprivate static final int DEFAULT_MAX_SIZE = 25;private int lastIndex; // index of last entry//******************************************************************
public MaxHeap( ) {heap = new Comparable[DEFAULT_MAX_SIZE];lastIndex = 0;
}//******************************************************************public MaxHeap(int maxSize) {
heap = new Comparable[maxSize];lastIndex = 0;
}//****************************************************************** public Comparable getMax( ) {
Comparable root = null;if (!isEmpty())
root = heap[1];return root;
}//******************************************************************public boolean isEmpty( ) {
return lastIndex < 1;}//******************************************************************public int getSize( ) {
return lastIndex;}//******************************************************************public void clear( ) {
for (; lastIndex > -1; lastIndex--)heap[lastIndex] = null;
lastIndex = 0;} //******************************************************************
...
Beginning class MaxHeap
9
Adding an Entry
Begin at next available position for a leaf
Follow path from this leaf toward root until correct position for new entry is found
As this is done• Move entries from parent to child• Makes room for new entry
13
Adding an EntryAlgorithm for adding new entry to a heap
public void add(Comparable newEntry) {lastIndex++;
if (lastIndex >= heap.length)
doubleArray(); // expand array
int newIndex = lastIndex;int parentIndex = newIndex/2;while ( (newIndex > 1) && newEntry.compareTo(heap[parentIndex]) > 0) {
heap[newIndex] = heap[parentIndex]; newIndex = parentIndex;
parentIndex = newIndex/2; }
heap[newIndex] = newEntry;
}
15
Removing the Root
Steps that transform a semiheap (i.e., a heap, except for the root) into a heap without swaps.
16
Removing the Root
To remove a heap's root• Replace the root with heap's last child
This forms a semiheap
Then use the method reheap• Transforms the semiheap to a heap
17
private void reheap(int rootIndex) {boolean done = false;Comparable orphan = heap[rootIndex];int largerChildIndex = 2*rootIndex; // index of left child, if any
while (!done && (largerChildIndex <= lastIndex) ) {int rightChildIndex = largerChildIndex + 1;if ( (rightChildIndex <= lastIndex) && heap[rightChildIndex].compareTo(heap[largerChildIndex]) > 0) {
largerChildIndex = rightChildIndex;}if (orphan.compareTo(heap[largerChildIndex]) < 0) {
heap[rootIndex] = heap[largerChildIndex];rootIndex = largerChildIndex;largerChildIndex = 2*rootIndex; // index of next left child
}else
done = true;}
heap[rootIndex] = orphan;}
18
public Comparable removeMax() {Comparable root = null;if (!isEmpty()) {
root = heap[1]; // return valueheap[1] = heap[lastIndex]; // form a
semiheaplastIndex--; // decrease sizereheap(1); // transform to a heap
} // end if
return root;} // end removeMax
20
Creating a Heap
The steps in creating a heap by using reheap.
More efficient to use reheap than to
use add
More efficient to use reheap than to
use add
21
public MaxHeap(Comparable[] entries) {lastIndex = entries.length;heap = new Comparable[lastIndex + 1];
// copy given array to data fieldfor (int index = 0; index < entries.length; index++)
heap[index+1] = entries[index];
// create heapfor (int index = heap.length/2; index > 0; index--)
reheap(index);}
Another Constructor for Class MaxHeap
Note: entries in array start at 0; entries in heap start at 1
22
Heapsort
Possible to use a heap to sort an array
Place array items into a maxheap
Then remove them• Items will be in descending order• Place them back into the original array and
they will be in order (but requires additional storage)
27
HeapsortImplementation of heapsort
public static void heapSort(Comparable[] array, int n) {// create first heapfor (int rootIndex = n/2-1; rootIndex >= 0; rootIndex--)
reheap(array, rootIndex, n-1);swap(array, 0, n-1);for (int lastIndex = n-2; lastIndex > 0; lastIndex--) {
reheap(array, 0, lastIndex);swap(array, 0, lastIndex);
} }
private static void reheap(Comparable[] heap, int rootIndex, int lastIndex) {// Similar to statements from previous code. See next page…. . .
}
What is the efficiency?What is the efficiency?
28
HeapsortImplementation of heapsort
public static void heapSort(Comparable[] array, int n) {// create first heapfor (int rootIndex = n/2-1; rootIndex >= 0; rootIndex--)
reheap(array, rootIndex, n-1);swap(array, 0, n-1);for (int lastIndex = n-2; lastIndex > 0; lastIndex--) {
reheap(array, 0, lastIndex);swap(array, 0, lastIndex);
} }
private static void reheap(Comparable[] heap, int rootIndex, int lastIndex) {// Similar to statements from previous code. See next page…. . .
}
Efficiency is O(n log n).
However, quicksort is usually a better choice.
Efficiency is O(n log n).
However, quicksort is usually a better choice.
29
private void reheap(reheap(Comparable[] heap, int rootIndex, int lastIndex) {boolean done = false;Comparable orphan = heap[rootIndex];int largerChildIndex = 2 * rootIndex + 1; // index of left child, if any
while (!done && (largerChildIndex <= lastIndex) ) {int rightChildIndex = largerChildIndex + 1;if ( (rightChildIndex <= lastIndex) && heap[rightChildIndex].compareTo(heap[largerChildIndex]) > 0)
{largerChildIndex = rightChildIndex;
}if (orphan.compareTo(heap[largerChildIndex]) < 0) {
heap[rootIndex] = heap[largerChildIndex];rootIndex = largerChildIndex;largerChildIndex = 2 * rootIndex + 1; // index of next left
child}else
done = true;}
heap[rootIndex] = orphan;}