我正在尝试在 Java 中实现 Min Heap,但在插入和删除元素时遇到问题(在末尾插入,以 min 删除根)。它似乎在大多数情况下都有效(我使用一个程序来直观地显示堆,并在删除 min 时打印出新的根,诸如此类)。
我的问题是,由于某种原因,添加新项目时根不会切换到新项目,但我根本不知道为什么。此外,这似乎只是有很多重复项时的问题,堆似乎并不完全能够保持有序(父项小于子项)。在大多数情况下,它确实如此。只是偶尔不会,对我来说这似乎是随机的。
这是通过泛型完成的,并且基本上遵循大多数算法。我所知道的所有其他事实都有效,这绝对是这两种方法的问题。
public void insert(T e) {
if (size == capacity)
increaseSize(); //this works fine
last = curr; //keeping track of the last index, for heapifying down/bubbling down when removing min
int parent = curr/2;
size++; //we added an element, so the size of our data set is larger
heap[curr] = e; //put value at end of array
//bubble up
int temp = curr;
while (temp > 1 && ((Comparable<T>) heap[temp]).compareTo(heap[parent]) < 0) { //if current element is less than the parent
//integer division
parent = temp/2;
swap(temp, parent); //the swapping method should be correct, but I included it for clarification
temp = parent; //just moves the index value to follow the element we added as it is bubbled up
}
curr++; //next element to be added will be after this one
}
public void swap(int a, int b){
T temp = heap[a];
heap[a] = heap[b];
heap[b] = temp;
}
public T removeMin() {
//root is always min
T min = heap[1];
//keep sure array not empty, or else size will go negative
if (size > 0)
size--;
//put last element as root
heap[1] = heap[last];
heap[last] = null;
//keep sure array not empty, or else last will not be an index
if (last > 0)
last--;
//set for starting at root
int right = 3;
int left = 2;
int curr = 1;
int smaller = 0;
//fix heap, heapify down
while(left < size && right < size){ //we are in array bounds
if (heap[left] != null && heap[right] != null){ //so no null pointer exceptions
if (((Comparable<T>)heap[left]).compareTo(heap[right]) < 0) //left is smaller
smaller = left;
else if (((Comparable<T>)heap[left]).compareTo(heap[right]) > 0) //right is smaller
smaller = right;
else //they are equal
smaller = left;
}
if (heap[left] == null || heap[right] == null)//one child is null
{
if (heap[left] == null && heap[right] == null)//both null, stop
break;
if (heap[left] == null)//right is not null
smaller = right;
else //left is not null
smaller = left;
}
if (((Comparable<T>)heap[curr]).compareTo(heap[smaller]) > 0)//compare smaller or only child
{
swap(curr,smaller); //swap with child
curr = smaller; //so loop can check new children for new placement
}
else //if in order, stop
break;
right = 2*curr + 1; //set new children
left = 2*curr;
}
return min; //return root
}
任何未在方法中声明的变量都是全局的,我知道有几件事可能是多余的,比如 add 中的整个当前/最后/临时情况,所以我很抱歉。我试图让所有名称都一目了然,并解释了我在 removeMin 中所做的所有检查。任何帮助将不胜感激,我已经尽我所能查找和调试。我想我只是从根本上错过了一些东西。