Below is a
BinaryHeap implementation using
Vector
I hope you don't get disappointed because I think
BinaryHeap is the easiest implementation over all of the Tree Data Structure that I've seen so far lol... Note the followings are the characteristics of
BinaryHeap:
1. Parent is always larger than the child
2. Child is always smaller than the parent
And the good news is that you don't have to worry to which sides of the parent's node should you put the children at, as long as both of them are smaller than the parent.
Just as usual, it is your own responsibility by using the code that I've written. It's been tested and worked at
JDK 6
PHP Code:
import java.util.Vector;
public class MyBinaryHeap {
protected Vector v = new Vector();
private int largest; // index of the largest
public void insert(Object in) {
v.add(in);
BUILD_MAX_HEAP();
}
public void remove() {
v.remove(v.size()-1);
}
public void MAX_HEAPIFY(int index) {
if (leftChild(index) < v.size() && Double.parseDouble(v.get(leftChild(index)).toString()) > Double.parseDouble(v.get(index).toString())) {
largest = leftChild(index);
} else {
largest = index;
}
if (rightChild(index) < v.size() && Double.parseDouble(v.get(leftChild(index)).toString()) > Double.parseDouble(v.get(index).toString())) {
largest = rightChild(index);
}
if (largest != index) {
swap(index, largest);
MAX_HEAPIFY(largest);
}
}
public void BUILD_MAX_HEAP() {
for (int i = v.size()/2; i >= 0; i--) {
MAX_HEAPIFY(i);
}
}
public void swap(int index, int largest) {
Object temp = new Object();
temp = v.get(index);
v.set(index, v.get(largest));
v.set(largest, temp);
}
public int parent(int i) {
return i/2;
}
public int leftChild(int i) {
return 2*i + 1;
}
public int rightChild(int i) {
return 2*i + 2;
}
}