我通过扩展ArrayList实现了Heap。但是,它似乎很好地作为minheap(与此代码差别不大),但它不能正常工作作为maxheap。我认为我有错误使用的部分或部分。我想知道出了什么问题或被误解了。
如果有更好的方法,如果你发表评论我会非常感激,谢谢。
class Heap<T extends Comparable<T>> extends ArrayList<T> {
public void insert(T elem) {
this.add(elem);
int idx = this.size() - 1;
if(idx > 0 && this.compare(idx, (idx - 1) / 2)){
Collections.swap(this, idx, (idx - 1) / 2);
idx = (idx - 1) / 2;
}
}
public void removeTop() {
if(this.size() == 1) {
this.remove(0);
return;
}
this.set(0, this.remove(this.size() - 1));
int here = 0;
while(true) {
int left = here * 2 + 1;
int right = here * 2 + 2;
if(left >= this.size()) break;
int next = here;
if(!this.compare(next, left)) {
next = left;
}
if(right < this.size() && !this.compare(next, right)){
next = right;
}
if(next == here) break;
Collections.swap(this, next, here);
here = next;
}
}
private void swap(int idx1, int idx2) {
T temp = this.get(idx1);
this.set(idx1, this.get(idx2));
this.set(idx2, temp);
}
private boolean compare(int idx1, int idx2) {
return this.get(idx1).compareTo(this.get(idx2)) >= 0;
}
}
(+)方法compare
用于根据类型比较两个元素。我希望在初始化堆时得到一种Compare function
。像...
Heap<Integer> heap = new Heap<Integer>(new SomekindofCompareFunction());
可以用Java吗?
答案 0 :(得分:1)
使用Comparator
:
class Heap<T> extends ArrayList<T> {
private final Comparator<T> comparator;
public Heap(Comparator<T> comparator) {
this.comparator = comparator;
}
...
private boolean compare(int idx1, int idx2) {
return comparator.compare(get(idx1), get(idx2)) >= 0;
}
}
您可以像这样创建Heap
:
Heap<Integer> heap = new Heap<Integer>((a,b) -> a.compareTo(b));