2012-06-30 29 views
0

我寫的堆排序的代碼如下: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() 
+1

附註......名爲變量list的真的不是一個好主意,因爲這已經是Python內置的。 – Amber

+1

我建議你將'length'方法改爲'__len__',這樣你就可以調用'len(myHeap)'並獲得這個長度。 – C0deH4cker

回答

2

self.firstself.last只是數據的副本載於self.list[0]self.list[-1]。您需要直接指定以下值:

self.data[0], self.data[-1] = self.data[-1], self.data[0] 

使用負數組索引會導致Python從末尾查看列表。此外,我建議使用data而不是list這樣的名稱來減少影響內置名稱list的機會。

2

應該self.list[0], self.list[-1] = self.list[-1], self.list[0]

self.firstself.last只是從self.list含有第一和最後一個值的變量,改變它們不會改變self.list