擅长:python、mysql、java
<pre><code>def insert(self, data):
self.heap.append(data)
self.heap_size = self.heap_size + 1
self.bubble_up(self.heap_size)
</code></pre>
<p>您可以附加数据,增加<code>heap_size</code>,然后使用新的(增加的)堆大小调用您的<code>bubble_up</code>。在</p>
<p>在那里,你可以检查:</p>
^{pr2}$
<p>其中<code>i</code>是堆大小。不能这样做,如果堆中有<code>3</code>个元素,则无法访问<code>heap[3]</code>。它不存在,您唯一有效的索引是<code>0, 1, 2</code>。在</p>
<p>可能的修复(未测试):用<code>heap_size - 1</code>调用<code>bubble_up</code>。在</p>
<p>请注意,<code>if</code>中的代码看起来并不正确:</p>
<pre><code>tmp = self.heap[i // 2 - 1] # why -1 here? shouldn't this be heap[i]?
self.heap[i] = self.heap[i // 2] # shouldn't this be the other way around? why no -1 here?
self.heap[i // 2] = tmp # why no -1 here? shouldn't this be heap[i]?
</code></pre>
<p>另外,您可以将<code>i // 2</code>放入该条件中,如果条件为false,则中断循环。在</p>