我寫的堆排序的代碼如下:Swap不適用於Python中的對象屬性?
有趣的是
self.first, self.last = self.last, self.first
未在列表self.list
的頭部和尾部交換兩個值。
爲什麼?
#heapsort
import pdb
class heap(object):
def __init__(self, list):
super(heap, self).__init__()
self.list = list
self.heapify()
if self.list:
self.first = self.list[0]
self.last = self.list[len(self.list)-1]
def length(self):
return len(self.list)
def heap_node(self,i):
large_i = i
if 2*i+1<self.length() and self.list[2*i+1]>self.list[i]:
large_i = 2*i+1
if 2*i+2<self.length() and self.list[2*i+2]>self.list[large_i]:
large_i = 2*i+2
if large_i!=i:
self.list[large_i], self.list[i] = self.list[i], self.list[large_i]
self.heap_node(large_i)
def heapify(self):
for i in range(self.length()/2,0,-1):
j=i-1
self.heap_node(j)
def sort(self):
# pdb.set_trace()
if not self.list:
return []
else:
# self.list[0], self.list[len(self.list)-1] = self.list[len(self.list)-1], self.list[0]
self.first, self.last = self.last, self.first
return heap(self.list[0:(self.length()-1)]).sort() + [self.list[len(self.list)-1]]
h=heap([1,3,2,5,4])
print h.list
print h.sort()
附註......名爲變量list的真的不是一個好主意,因爲這已經是Python內置的。 – Amber
我建議你將'length'方法改爲'__len__',這樣你就可以調用'len(myHeap)'並獲得這個長度。 – C0deH4cker