gpt4 book ai didi

python - 获取错误的数组排序(用Python编写堆排序)

转载 作者:太空宇宙 更新时间:2023-11-03 19:11:22 25 4
gpt4 key购买 nike

我编写了以下堆排序代码,有时会得到错误的输出(未排序),我似乎找不到原因......任何帮助将不胜感激! (警告:我仍在学习 Python,这可能是问题所在)

def heap_sort(self, a):

self.build_max_heap(a)
n = len(a)-1
i = len(a)-1

for i in range(len(a)-1, 1):
temp = a[0]
a[0] = a[i]
a[i] = temp
a.heapsize = heapsize - 1
self.max_heapify(a, 0) #rebuild max heap at with new root



def max_heapify(self, a, i):

left = (2*(i+1))-1 #left child of i
right = 2*(i+1) #right child of i
largest = i

if left < a.heapsize and a[left] > a[i]:
largest = left

if right < a.heapsize and a[right] > a[largest]:
largest = right

if largest != i:
temp = a[largest]
a[largest] = a[i]
a[i] = temp
self.max_heapify(a, largest)



def build_max_heap(self, a):

heapsize = len(a)
i = int(heapsize/2)-1

for i in range(i, 0):
self.max_heapify(a, i)

这些是我的测试:

#--Test for 0 in array--#
def zero_array(self):
a = [12,0,232]
print self.sort.heap_sort(a)
return

#--Test for duplicate in array--#
def duplicate_array(self):
a = [12, 12, 7]
print self.sort.heap_sort(a)
return

#--Test for all same values in array--#
def allsame_array(self):
a = [1,1,1]
print self.sort.heap_sort(a)
return

#--Test for negative values in array--#
def negative_array(self):
a = [-23, -2, 123]
print self.sort.heap_sort(a)
return

我得到以下返回的数组(假设已排序):

    [12, 0, 232]
[12, 12, 7]
[1, 1, 1]
[-23, -2, 123]

最佳答案

我立即发现一个问题:

for i in range(len(a)-1, 1)

如果您想减少到 1 次包含使用:

for i in range(len(a)-1, 0, -1)

关于python - 获取错误的数组排序(用Python编写堆排序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12898926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com