当需要订购超过 2 个数字时,MaxHeapify 的构造函数出现问题。单步执行代码,它适用于前几个,然后在没有正确排序数字的情况下继续。我不确定为什么这不起作用,任何关于我似乎在这里混淆的变量或比较的帮助将不胜感激。
public class MaxHeap
{
public int[] heap;
public int index_to_last_element;
protected void maxHeapify(int index)
{
int left = leftchild(index);
int right = rightchild(index);
int largest = index;
if (left < index_to_last_element && left != -1 && heap[left] > heap[index])
largest = left;
if (right < index_to_last_element && right != -1 && heap[right] > heap[largest])
largest = right;
if (largest != index)
{
int temp = heap[index];
heap[index] = heap[largest];
heap[largest] = temp;
maxHeapify(largest);
}
}
public int parent(int pos)
{
return (pos - 1) / 2;
}
public int leftchild(int pos)
{
return 2 * pos + 1;
}
public int rightchild(int pos)
{
return 2 * pos + 2;
}