package Heap;
import java.util.Comparator;
//使用数组实现最大堆
//以节点第i个元素为例
//左右子节点分别为2*i+1, 2*i+2 父节点为(i-1)/2
public class Heap {
//增加元素
public static <T> void pushHeap(T[] arr, int last,T item, Comparator<? super T> comp){
int currPos,parentPos;
currPos = last;
parentPos = (currPos-1)/2;
while(currPos != 0){
//父节点的元素小于当前元素,则把父节点的值,复制到子节点
if( comp.compare( item, arr[parentPos] ) < 0 ){
arr[currPos] = arr[parentPos];
currPos = parentPos;
parentPos= (currPos-1)/2;
}
else{
break;
}
}//end while
arr[currPos] = item;
}//end pushHeap
//删除元素
public static <T> T popHeap(T[] arr, int last,Comparator<? super T> comp){
T temp = arr[0];
arr[0] = arr[last-1];
arr[last-1] = temp;
adjustHeap(arr, 0, last-1, comp);
return temp;
}
//调整堆顶点使其成为最大堆
public static <T> void adjustHeap(T[] arr, int first, int last,Comparator<? super T> comp){
int currPos,childPos;
T target;
currPos = first;
target = arr[first];
childPos = currPos*2+1;
while(childPos < last){
if((childPos+1 < last) &&comp.compare(arr[childPos+1], arr[childPos]) < 0){
childPos =childPos + 1;
}
if (comp.compare(arr[childPos],target) < 0){
arr[currPos] = arr[childPos];
currPos = childPos;
childPos = currPos*2 +1;
}
else{
break;
}
}//end whiel
arr[currPos] = target;
}//end abjustHeap()
//数组的堆化,最大堆要求每个节点的值都大于子节点,因此叶子节点都满足最大堆
//最后一个内节点为((last-1)-1)/2=(last-2)/2
//把每个子堆都变成最大堆,最后就形成了一个最大堆
public static<T> void makeHeap(T arr[],Comparator<? super T> comp){
int heapPos, lastPos;
lastPos = arr.length;
heapPos = (lastPos-2)/2;
while(heapPos >= 0){
adjustHeap(arr, heapPos, lastPos, comp);
heapPos --;
}
}//end makeheap()
//堆排序
public static <T> void heapSort(T[] arr, Comparator<? super T> comp){
Heap.makeHeap(arr, comp);
int i, n = arr.length;
for(i = n ; i > 1 ; i--){
Heap.popHeap(arr, i, comp);
}
}
}
package Heap;
import java.util.Comparator;
import java.util.NoSuchElementException;
import 算法.PQueue;
//优先队列的实现
public class HeapPQueue<T> implements PQueue<T> {
private T[] heapElt;
private int numElt;
private Comparator<T> comp;
public HeapPQueue(){
comp = new Less<T>();
numElt = 0;
heapElt =(T[]) new Object[10];
}
public void push(T item) {
if(numElt == heapElt.length){
enlargeCapacity();
}
Heap.pushHeap(heapElt, numElt, item, comp);
numElt ++;
}
private void enlargeCapacity() {
T[] oldHeapElt = heapElt;
T[] newHeapElt =(T[]) new Object[heapElt.length * 2];
for(int i = 0; i < oldHeapElt.length; i++){
newHeapElt[i] = oldHeapElt[i];
}
heapElt = newHeapElt;
oldHeapElt = null;
}
@Override
public T pop() {
if(numElt == 0){
throw new NoSuchElementException();
}
T top = Heap.popHeap(heapElt, numElt, comp);
numElt -- ;
return top;
}
@Override
public T peek() {
if(numElt == 0){
throw new NoSuchElementException();
}
return heapElt[0];
}
@Override
public boolean isEmpty() {
return numElt == 0;
}
@Override
public int size() {
return numElt;
}
}