gpt4 book ai didi

java - 需要帮助计算 MaxHeap 中的交换数量

转载 作者:行者123 更新时间:2023-12-02 01:32:47 24 4
gpt4 key购买 nike

我目前正在开发一个必须创建最大堆的项目。我目前正在使用我的教科书版本的堆,它看起来像:

public MaxHeap(int initialCapacity) {
if (initialCapacity < DEFAULT_CAPACITY)
initialCapacity = DEFAULT_CAPACITY;
else
checkCapacity(initialCapacity);

@SuppressWarnings("unchecked")
T[] tempHeap = (T[]) new Comparable[initialCapacity + 1];
heap = tempHeap;
lastIndex = 0;
initialized = true;
}

public T getMax() {
checkInitialization();
T root = null;
if (!isEmpty())
root = heap[1];
return root;
}

public boolean isEmpty() {
return lastIndex < 1;
}

public int getSize() {
return lastIndex;
}

public void clear() {
checkInitialization();
while (lastIndex > -1) {
heap[lastIndex] = null;
lastIndex--;
}
lastIndex = 0;
}

public void add(T newEntry) {
checkInitialization();
int newIndex = lastIndex + 1;
int parentIndex = newIndex / 2;
while ((parentIndex > 0) && newEntry.compareTo(heap[parentIndex]) > 0) {
heap[newIndex] = heap[parentIndex];
newIndex = parentIndex;
parentIndex = newIndex / 2;
}
heap[newIndex] = newEntry;
lastIndex++;
ensureCapacity();
}

public int getSwaps()
{
return swaps;
}

public T removeMax() {
checkInitialization();
T root = null;
if (!isEmpty()) {
root = heap[1];
heap[1] = heap[lastIndex];
lastIndex--;
reheap(1);
}
return root;
}

private void reheap(int rootIndex) {
boolean done = false;
T orphan = heap[rootIndex];
int leftChildIndex = 2 * rootIndex;

while (!done && (leftChildIndex <= lastIndex)) {
int largerChildIndex = leftChildIndex;
int rightChildIndex = leftChildIndex + 1;
if ((rightChildIndex <= lastIndex) && heap[rightChildIndex].compareTo(heap[largerChildIndex]) > 0) {
largerChildIndex = rightChildIndex;
}
if (orphan.compareTo(heap[largerChildIndex]) < 0) {
heap[rootIndex] = heap[largerChildIndex];
rootIndex = largerChildIndex;
leftChildIndex = 2 * rootIndex;
} else
done = true;
}
heap[rootIndex] = orphan;

}

我是否应该在多个地方计算掉期并打印总金额,如果是的话我会在哪里计算它们?我之前曾尝试在 add 方法中枚举 swaps++,但我认为这不是正确的方法。

最佳答案

您必须计算 add(T newEntry) 方法和从 removeMax 方法调用的 reHeap 方法中的交换。

reHeap中,您从顶部开始,当您从removeMax调用它时,在删除最大值(在最大堆情况下)后,您将根替换为最后一个元素,然后您需要平衡堆。因此堆递归地下降到最后一层以达到平衡,这可能需要交换。

编辑:

reHeap的以下代码块中添加交换:

if (orphan.compareTo(heap[largerChildIndex]) < 0) {
heap[rootIndex] = heap[largerChildIndex];
rootIndex = largerChildIndex;
leftChildIndex = 2 * rootIndex;
// increment the swap here as inside this block of reHeap only swap takes place.
swap++
}

关于java - 需要帮助计算 MaxHeap 中的交换数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55797366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com