什么是堆:
堆是一种重要的数据结构,构建堆的结构大致分为两种,分别是大根堆合小根堆。比如一颗完全二叉树,可以构建父节点大于所有字点的大根堆,也可以构建父节点小于所有子节点的小根堆。其实堆就是一颗完全二叉树,实现堆可以调整数组中当前节点i和i*2+1的位置与(i-1)/2的位置关系就好。
增强堆
增强堆就是在原来只有键的索引的基础上加入了值的索引,带有反向索引表的堆,代码如下。
package class06;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import class05.code_heapSort;
public class HeapGreatertest {
public class HeapGreater<T>{
private ArrayList<T> heap;
private HashMap<T, Integer> indexMap;
private int heapsize;
private Comparator<? super T> comp;
public HeapGreater(Comparator<T> c){
heap = new ArrayList<>();
indexMap = new HashMap<>();
heapsize = 0;
comp = c;
}
public boolean isEmpty() {
return heapsize ==0;
}
public int size() {
return heapsize;
}
public boolean contains(T obj) {
return indexMap.containsKey(obj);
}
public T peek() {
return heap.get(0);
}
public void push(T obj) {
heap.add(obj);
indexMap.put(obj, heapsize);
heapInsert(heapsize++);
}
public T pop() {
T ans = heap.get(0);
swap(0,heapsize-1);
indexMap.remove(ans);
heap.remove(--heapsize);
heapify(0);
return ans;
}
public void remove (T obj) {
T replace = heap.get(heapsize-1);
int index = indexMap.get(obj);
indexMap.remove(obj);
heap.remove(--heapsize);
if(obj!=replace) {
heap.set(index, replace);
indexMap.put(replace, index);
resign(replace);
}
}
private void resign(T obj) {
heapInsert(indexMap.get(obj));
heapify(indexMap.get(obj));
}
//返回堆上1所有元素
public List<T> getAllElements(){
List<T> ans = new ArrayList<>();
for(T c : heap) {
ans.add(c);
}
return ans;
}
private void heapify(int index) {
int left = index*2+1;
while(left<heapsize) {
int best = left+1<heapsize&&comp.compare(heap.get(left), heap.get(left+1))<0?left+1:left;
best = comp.compare(heap.get(best), heap.get(index))<0?best:index;
if(best == index) break;
swap(best, index);
index = best;
left = index*2+1;
}
}
private void swap(int i, int j) {
T o1 = heap.get(i);
T o2 = heap.get(j);
heap.set(j, o1);
heap.set(i, o2);
indexMap.put(o2,i);
indexMap.put(o1,j);
}
private void heapInsert(int index) {
while(comp.compare(heap.get(index), heap.get((index-1)/2))<0){
swap(index, (index-1)/2);
index = (index-1)/2;
}
}
}
}