def percDown(self, i): while (i * 2) <= self.currentSize: mc = self.minChild(i) if mc <=0: break if self.heapArray[i][0] > self.heapArray[mc][0]: self.heapArray[i], self.heapArray[mc] = self.heapArray[mc], self.heapArray[i] i = mc有问题吗
时间: 2024-02-14 13:05:16 浏览: 26
这段代码是堆排序中的“下滤”操作,用于保证堆的性质。代码看起来没有问题,但是建议将第 4 行的条件修改为 mc < 0,因为当前节点的索引 i 是大于等于 1 的,如果 mc 小于等于 0,则说明当前节点 i 没有子节点了,这种情况下应该退出循环。
修改后的代码如下:
```
def percDown(self, i):
while (i * 2) <= self.currentSize:
mc = self.minChild(i)
if mc < 0:
break
if self.heapArray[i][0] > self.heapArray[mc][0]:
self.heapArray[i], self.heapArray[mc] = self.heapArray[mc], self.heapArray[i]
i = mc
```
这样修改之后,代码更加严谨,可以避免出现不必要的循环。
相关问题
def percDown(self, i): while (i * 2) <= self.currentSize: mc = self.minChild(i) if mc < 0: break if self.heapArray[i][0] > self.heapArray[mc][0]: self.heapArray[i], self.heapArray[mc] = self.heapArray[mc], self.heapArray[i] i = mc def minChild(self, i): if i * 2 > self.currentSize: return -1 else: if i * 2 + 1 > self.currentSize: return i * 2 else: if self.heapArray[i * 2-1][0] < self.heapArray[i * 2][0]: # 修改 return i * 2 else: return i * 2 + 1i = len(alist) // 2 while (i > 0): pq.percDown(i) i = i - 1查找错误并修改
在minChild函数中,第7行代码需要修改为`if self.heapArray[i * 2][0] < self.heapArray[i * 2 + 1][0]:`,因为原代码中比较的是`self.heapArray[i * 2-1][0]`和`self.heapArray[i * 2][0]`,但是这是错误的,应该比较的是左右子节点的大小。修改后的代码如下:
```
def percDown(self, i):
while (i * 2) <= self.currentSize:
mc = self.minChild(i)
if mc < 0:
break
if self.heapArray[i][0] > self.heapArray[mc][0]:
self.heapArray[i], self.heapArray[mc] = self.heapArray[mc], self.heapArray[i]
i = mc
def minChild(self, i):
if i * 2 > self.currentSize:
return -1
else:
if i * 2 + 1 > self.currentSize:
return i * 2
else:
if self.heapArray[i * 2][0] < self.heapArray[i * 2 + 1][0]: # 修改
return i * 2
else:
return i * 2 + 1
i = len(alist) // 2
while (i > 0):
pq.percDown(i)
i = i - 1
```
def minChild(self, i): if i * 2 > self.currentSize: return -1 else: if i * 2 + 1 > self.currentSize: return i * 2 else: if self.heapArray[i * 2][0] < self.heapArray[i * 2 + 1][0]: return i * 2 else: return i * 2 + 1
这段代码是一个找到当前节点 i 的权重最小的子节点的 minChild 方法的实现,与我之前给出的实现几乎相同,只是在第一步判断是否有左子节点时,将判断条件改为了 i * 2 > self.currentSize。
这样的判断条件是错误的,因为当左子节点的索引 i * 2 等于当前堆的大小 self.currentSize 时,左子节点仍然是存在的。因此,应该将判断条件改为 i * 2 <= self.currentSize。
因此,可以将代码修改为以下形式:
```
def minChild(self, i):
if i * 2 > self.currentSize:
return -1
else:
if i * 2 + 1 > self.currentSize:
return i * 2
else:
if self.heapArray[i * 2][0] < self.heapArray[i * 2 + 1][0]:
return i * 2
else:
return i * 2 + 1
```
修改后的代码将判断条件改为了 i * 2 <= self.currentSize,确保了左子节点的存在性。同时,如果当前节点没有子节点,返回 -1,表示没有权重最小的子节点。