Python heapify实现运行时
我正在学习一门关于数据结构和算法的课程,我本应该在指定的时间范围内实现heapsort算法。以下是两种实现方式:Python heapify实现运行时,python,algorithm,heap,binary-heap,Python,Algorithm,Heap,Binary Heap,我正在学习一门关于数据结构和算法的课程,我本应该在指定的时间范围内实现heapsort算法。以下是两种实现方式: def generateSwaps(): size=self._n for root in range((size//2)-1,-1,-1): root_val = self._data[root] # save root value child = 2*root+1 while(child<siz
def generateSwaps():
size=self._n
for root in range((size//2)-1,-1,-1):
root_val = self._data[root] # save root value
child = 2*root+1
while(child<size):
if child<size-1 and self._data[child]>self._data[child+1]:
child+=1
if root_val<=self._data[child]: # compare against saved root value
break
self._data[(child-1)//2]=self._data[child] # find child's parent's index correctly
self._swaps.append(((child-1)//2,child))
child=2*child+1
# print(child)
self._data[(child-1)//2]=root_val # here too, and assign saved root value
return self._data
def generateSwaps():
尺寸=自身尺寸
对于范围((大小//2)-1,-1,-1)中的根:
root_val=self._data[root]#保存根值
child=2*root+1
而(child正如上面评论中的user2357112和user2357112所建议的,问题是下面一行中的.index()操作
child_index = self._data.index(min(self._data[(2*i) + 1],self._data[(2*i) + 2]))
查找数组中元素的索引的运行时间为O(n)因为它需要遍历数组,直到找到值的第一个匹配项。这导致第二个实现中的运行时间过长。在第一个实现中,这已被替换为直接比较所考虑的子项及其相邻子项的值,如下所示
if child<size-1 and self._data[child]>self._data[child+1]:
child+=1
if childself.\u数据[child+1]:
儿童+=1
由于数组对元素的访问时间是固定的,因此上面的实现是固定时间的,从而减少了运行时间。正如上面的注释中user2357112和user2357112所建议的,问题在于下面一行中的.index()操作
child_index = self._data.index(min(self._data[(2*i) + 1],self._data[(2*i) + 2]))
查找数组中元素的索引的运行时间为O(n)因为它需要遍历数组,直到找到值的第一个匹配项。这导致第二个实现中的运行时间过长。在第一个实现中,这已被替换为直接比较所考虑的子项及其相邻子项的值,如下所示
if child<size-1 and self._data[child]>self._data[child+1]:
child+=1
if childself.\u数据[child+1]:
儿童+=1
由于数组对元素的访问时间是固定的,所以上面的实现是固定时间的,从而减少了运行时间。self.\u data.index(…)
-你为什么要调用索引
?这太慢了,毫无必要。如果你发现自己调用索引
,停下来试着找到更好的方法。这通常是个坏主意。谢谢你指出。这解决了我的问题。我错误地将查找索引计算为一个常量时间操作。self.\u data.index(…)
-你为什么要调用索引
?这太慢了,毫无必要。如果你发现自己调用索引
,停下来试着找到更好的方法。这通常是个坏主意。谢谢你指出。这解决了我的问题。我错误地将查找索引计算为一个常量时间操作。fwiw,user2357112和user2357112是同一个人…:)fwiw、user2357112和user2357112是同一个人…:)