如何将二进制堆排序转换为d_ary堆排序?
嗨,我有一种算法,该算法使用二进制树来堆积,然后对我需要转换此类算法的列表将其更改为D-Heap或d-ary heap或k-ary heap 我的代码在这里
def build_heap(lista, num):
"""Function to construct heap."""
for i in range(num // 2 - 1, -1, -1):
heapify(lista, num, i)
def heapify(lista, num, index):
"""Function to heapify list."""
largest = index
left = (2 * index) + 1
right = (2 * index) + 2
if left < num and lista[largest] < lista[left]:
largest = left
if right < num and lista[largest] < lista[right]:
largest = right
if largest != index:
lista[index], lista[largest] = lista[largest], lista[index]
heapify(lista, num, largest)
def heapsort(lista,d=2):
"""Function for final Heap sort."""
length = len(lista)
build_heap(lista, length)
for i in range(length - 1, 0, -1):
lista[i], lista[0] = lista[0], lista[i]
heapify(lista, i, 0)
请帮忙
Hi I have an algorithm that uses binary tree to heapify and then sort the list i need to convert this sort algorithm to change into d-heap or d-ary heap or k-ary heap
my code is here
def build_heap(lista, num):
"""Function to construct heap."""
for i in range(num // 2 - 1, -1, -1):
heapify(lista, num, i)
def heapify(lista, num, index):
"""Function to heapify list."""
largest = index
left = (2 * index) + 1
right = (2 * index) + 2
if left < num and lista[largest] < lista[left]:
largest = left
if right < num and lista[largest] < lista[right]:
largest = right
if largest != index:
lista[index], lista[largest] = lista[largest], lista[index]
heapify(lista, num, largest)
def heapsort(lista,d=2):
"""Function for final Heap sort."""
length = len(lista)
build_heap(lista, length)
for i in range(length - 1, 0, -1):
lista[i], lista[0] = lista[0], lista[i]
heapify(lista, i, 0)
please help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将
d
参数添加到您的所有功能中,并概括。在哪里开始堆功能的公式为(num + 1)// D -1
。在哪里有左
和右
索引,然后选择具有最大价值的索引,而是在 loop中迭代儿童以找到孩子具有最大的价值。Add the
d
parameter to all your functions, and generalise. The formula for where to start the heapify function is(num + 1) // d - 1
. Where you haveleft
andright
indices and choose the one that has the greatest value, instead iterate the children in afor
loop to find the child with the greatest value.