18/9/2007 I2A 98 slides 12
1
Richard Bornat Dept of Computer Science
The beautiful binary heap. Weiss has a chapter on the binary heap - - - PDF document
The beautiful binary heap. Weiss has a chapter on the binary heap - chapter 20, pp581-601. Its a very neat implementation of the binary tree idea, using an array. We can use the binary heap to sort an array, and we can use it to make a
18/9/2007 I2A 98 slides 12
Richard Bornat Dept of Computer Science
18/9/2007 I2A 98 slides 12
Richard Bornat Dept of Computer Science
A B D E H I J C F G
18/9/2007 I2A 98 slides 12
Richard Bornat Dept of Computer Science
A B D E H I J C F G L M N O K P
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
18/9/2007 I2A 98 slides 12
Richard Bornat Dept of Computer Science
class Element { public Key k; public Data d; } class BinaryHeap { private Element[] H; int count; // number of things in the heap ... }
18/9/2007 I2A 98 slides 12
Richard Bornat Dept of Computer Science
÷
i i
2
18/9/2007 I2A 98 slides 12
Richard Bornat Dept of Computer Science
18/9/2007 I2A 98 slides 12
Richard Bornat Dept of Computer Science
18/9/2007 I2A 98 slides 12
Richard Bornat Dept of Computer Science
public void insert(Key k, Data d) { count++; bubbleup(k,d,count); // H[1..count] are valid elements } private void bubbleup(Key k, Data d, int i) { int j; for (; j=i/2, i!=1 && !H[j].key.lesseq(k); i=j) H[i]=H[j]; H[i].key=k; H[i].data=d; }
18/9/2007 I2A 98 slides 12
Richard Bornat Dept of Computer Science
class Stopper implements Key { public boolean equals(Key k) { return k instanceof Stopper; } public boolean lesseq(Key k) { return true; } }
18/9/2007 I2A 98 slides 12
Richard Bornat Dept of Computer Science
18/9/2007 I2A 98 slides 12
Richard Bornat Dept of Computer Science
18/9/2007 I2A 98 slides 12
Richard Bornat Dept of Computer Science
public Data remove() { Data d = H[1].d; H[1]=H[count--]; bubbledown(1); return d; } public void bubbledown(int i) { Element r = H[i]; int j; for (; j=i*2, j<=count; i=j) { if (j+1<=count && H[j+1].k.lesseq(H[j].k)) j++; // pick left or right child if (r.k.lesseq(H[j].k)) break; // exit if in order else H[i]=H[j]; } H[i]=r; }
18/9/2007 I2A 98 slides 12
Richard Bornat Dept of Computer Science
18/9/2007 I2A 98 slides 12
Richard Bornat Dept of Computer Science
for (int i=count/2; i>0; i--) bubbledown(i);
Element r = H[1]; remove(); H[count+1]=r;
count 1..
18/9/2007 I2A 98 slides 12
Richard Bornat Dept of Computer Science