publicclass Heap<E extends Comparable<E>> {
private ArrayList<E> list = new ArrayList<>();
// create a default heappublic Heap() {
}
// create a heap from an array of objectspublic Heap(E[] objects) {
for (int i = 0; i < objects.length; i++) {
add(objects[i]);
}
}
// add a new object into the heappublicvoid add(E newObject) {
list.add(newObject);
int currentIndex = list.size() - 1;
// swap if the current object is greater than its parentswhile (currentIndex > 0) {
int parentIndex = (currentIndex - 1) / 2;
if (list.get(currentIndex).compareTo(list.get(parentIndex)) > 0) {
E temp = list.get(currentIndex);
list.set(currentIndex, list.get(parentIndex));
list.set(parentIndex, temp);
} elsebreak;
currentIndex = parentIndex;
}
}
// remove the root from the heappublic E remove() {
if (list.size() == 0)
return null;
E removeObject = list.get(0);
list.set(0, list.get(list.size() - 1));
list.remove(list.size() - 1);
int currentIndex = 0;
while (currentIndex < list.size()) {
int leftChildIndex = 2 * currentIndex + 1;
int rightChildIndex = 2 * currentIndex + 2;
// find the maximum between two childrenif (leftChildIndex >= list.size())
break;// 此时已经在堆的最底层int maxIndex = leftChildIndex;
if (rightChildIndex < list.size()) {
if (list.get(maxIndex).compareTo(list.get(rightChildIndex)) < 0)
maxIndex = rightChildIndex;
}
// swap if the current node is less than the maximumif (list.get(currentIndex).compareTo(list.get(maxIndex)) < 0) {
E temp = list.get(maxIndex);
list.set(maxIndex, list.get(currentIndex));
list.set(currentIndex, temp);
currentIndex = maxIndex;
} elsebreak;// the tree is a heap
}
return removeObject;
}
publicint getSize() {
returnlist.size();
}
使用heap类进行排序:
publicclass HeapSort {
publicstaticvoidmain(String[] args) {
Integer[] list = { -44, -5, -3, 3, 3, 1, -4, 0, 1, 2, 4, 5, 53 };
heapSort(list);
System.out.print("{-44,-5,-3,3,3,1,-4,0,1,2,4,5,53}" + " by HeapSort is\n{");
for (int i = 0; i < list.length; i++) {
System.out.print(list[i] + ",");
}
System.out.println("}");
}
publicstatic <E extends Comparable<E>> voidheapSort(E[] list) {
// Create a heap of integers
Heap<E> heap = new Heap<>();
// Add elements to the heapfor (int i = 0; i < list.length; i++)
heap.add(list[i]);
for (int i = list.length - 1; i >= 0; i--) {
list[i] = heap.remove();
}
}
}