如何在Python的堆数据结构中实现max_heapify
下面是堆的一个类。我正在尝试对堆进行排序,但我的如何在Python的堆数据结构中实现max_heapify,python,data-structures,Python,Data Structures,下面是堆的一个类。我正在尝试对堆进行排序,但我的max\u heapify函数有问题。我已经插入了值[10,9,7,6,5,4,3],我的堆排序打印出给定的输出。给定输出和预期输出在类下面给出 堆类 class Heap(object): def __init__(self): self.A = [] def insert(self, x): self.A.append(x) def Max(self): """
max\u heapify
函数有问题。我已经插入了值[10,9,7,6,5,4,3]
,我的堆排序打印出给定的输出。给定输出和预期输出在类下面给出
堆类
class Heap(object):
def __init__(self):
self.A = []
def insert(self, x):
self.A.append(x)
def Max(self):
"""
returns the largest value in an array
"""
return max(self.A)
def extractMax(self):
"""
returns and remove the largest value from an array
"""
x = max(self.A)
self.A.remove(x)
self.max_heapify(0)
return x;
def parent(self, i):
"""
returns the parent index
"""
i+=1
i = int(i/2)
return i
def left(self, i):
"""
returns the index of left child
"""
i = i+1
i = 2*i
return i
def right(self, i):
"""
returns the index of right child
"""
i+=1;
i = 2*i + 1
return i
def heap_size(self):
"""
returns the size of heap
"""
return len(self.A)
def max_heapify(self, i):
"""
heapify the array
"""
l = self.left(i)
r = self.right(i)
if(l < self.heap_size() and self.A[l] > self.A[i]):
largest = l
else:
largest = i
if(r < self.heap_size() and self.A[r] > self.A[largest]):
largest = r
if largest != i:
temp = self.A[i]
self.A[i] = self.A[largest]
self.A[largest] = temp
self.max_heapify(largest)
def build_max_heap(self):
n = len(self.A)
n = int(n/2)
for i in range(n, -1, -1):
self.max_heapify(i)
def heap_sort(self):
"""
sorts the heap
"""
while self.heap_size() > 0:
self.build_max_heap()
temp = self.A[0]
n = len(self.A) - 1
self.A[0] = self.A[n]
self.A[n] = temp
x = self.A.pop()
print(x)
self.max_heapify(0)
h = Heap()
h.insert(10)
h.insert(9)
h.insert(7)
h.insert(6)
h.insert(5)
h.insert(4)
h.insert(3)
h.heap_sort()
预期产量
10
9
7
6
5
4
3
看起来您正试图构建一个最大堆,其根位于
a[0]
。如果这是正确的,那么您的左
、右
和父
索引计算不正确。你有:
def parent(self, i):
"""
returns the parent index
"""
i+=1
i = int(i/2)
return i
def left(self, i):
"""
returns the index of left child
"""
i = i+1
i = 2*i
return i
def right(self, i):
"""
returns the index of right child
"""
i+=1;
i = 2*i + 1
return i
因此,如果i=0
,左边的子项将是2,右边的子项将是3。更糟糕的是,给定i=3
,parent
将返回2。所以你有一个例子,parent(right(i))!=我
。那是行不通的
正确的计算是:
left = (2*i)+1
right = (2*i)+2
parent = (i-1)/2
我不知道为什么您的extractMax
正在调用max(self.A)
。您已经知道最大元素位于A[0]
。要提取最大项,只需执行以下操作:
returnValue = save value at self.A[0]
take last item in the array and place at self.A[0]
decrease length of array
maxHeapify(0)
while self.heap_size() > 0:
temp = self.extractMax()
print temp
我使用伪代码是因为我对Python不是特别熟悉
heapSort
方法中的循环严重非最佳。您在每次迭代中调用的是self.build\u max\u heap。你不需要那样做。如果extractMax
工作正常,则只需执行以下操作:
returnValue = save value at self.A[0]
take last item in the array and place at self.A[0]
decrease length of array
maxHeapify(0)
while self.heap_size() > 0:
temp = self.extractMax()
print temp
现在,如果您想对数组进行适当的排序,以便对
self.A
本身进行排序,这就有点棘手了。但看起来这不是你想要做的。@Grokify谢谢你的编辑