我寫了下面的堆排序的代碼堆排序(用Python編寫的),我得到錯誤的輸出(未排序)的時間,我似乎無法找到爲什麼...任何幫助將是非常感激!錯誤輸出
def heap_sort(self, a):
heapsize = self.build_max_heap(a)
n = len(a)-1
i = len(a)-1
for i in range(i, 0, -1):
temp = a[0]
a[0] = a[i]
a[i] = temp
heapsize = heapsize - 1
self.max_heapify(heapsize, a, 0) #rebuild max heap at with new root
return a
def max_heapify(self, heapsize, a, i):
left = (2*(i+1))-1 #left child of i
right = 2*(i+1) #right child of i
largest = i
if left < heapsize and a[left] > a[i]:
largest = left
if right < heapsize and a[right] > a[largest]:
largest = right
if largest != i:
temp = a[largest]
a[largest] = a[i]
a[i] = temp
self.max_heapify(heapsize, 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(heapsize, a, i)
return heapsize
我的測試:
#--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
輸出(這是應該的所有排序):
[0, 232, 12]
[7, 12, 12]
[1, 1, 1]
[-2, 123, -23]
無需一個'temp'變量,你可以做一個'[0],A [1] = A [1],A [0]'。你也不會用'n'做任何事情。 –
你說「有時」這是否意味着輸出有時會正確排序? –
你可以從我的測試,我測試陣列的不同場景被髮送到進行排序看......有的,你可以在輸出工作看,有些卻沒有......(@彌敦道 - 第n做一些事情否則,我註釋掉測試初始化,維護和終止,爲不具有溫度,我不明白你更換[I] = A [1]? – Baraa