Info iconThis preview shows page 1. Sign up to view the full content.

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

Unformatted text preview: e root with node at end, then sink it down. Remove the maximum. Exchange root with node at end, then sink it down. heap ordered heap ordered S T P R N H E I T R O A N G P R H O A E I G G P E N O H I S A R O N P G A E I H 21 Binary heap: Java implementation 22 Priority queues implementation cost summary public class MaxPQ<Key extends Comparable<Key>> { private Key pq; private int N; order-of-growth of running time for priority queue with N items implementation private void swim(int k) private void sink(int k) { /* see previous code */ 1 N N ordered array N 1 1 log N log N 1 d-ary heap logd N d logd N 1 Fibonacci 1 1 log N 1 impossible } max Brodal queue public boolean isEmpty() { return N == 0; } public void insert(Key key) public Key delMax() { /* see previous code */ } del max unordered array fixed capacity (for simplicity) insert binary heap public MaxPQ(int capacity) { pq = (Key) new Comparable[capacity+1]; 1 1 1 } PQ ops heap helper functions private boolean less(int i, int j) { return pq[i].compareTo(pq[j]) < 0; } private void exch(int i, int j) { Key t = pq[i]; pq[i] = pq[j]; pq[j] = t; array helper functions } log N † 1 why impossible? † amortized } 23 24 Binary heap considerations Immutability: implementing in Java Immutability of keys. Data type. Set of values and operations on those values. ・Assumption: client does not change keys while they're on the PQ. ・Best practice: use immutable keys. Immutable data type. Can't change the data type value once created. public final class Vector { private final int N; private final double data; Underflow and overflow. ・Underflow: throw exception if deleting from empty PQ. ・Overflow: add no-arg constructor and use resizing array. can't override instance methods instance variables private and final public Vector(double data) { this.N = data.length; = new double[N]; for (int i = 0; i < N; i++)[i] = data[i]; } ・Replace less() with greater(). ・Implement greater(). instance methods d...
View Full Document

This document was uploaded on 02/20/2014 for the course COS 226 at Princeton.

Ask a homework question - tutors are online