2017-06-01 94 views
-2

我一直在尋找並嘗試這麼多,但無法弄清楚如何使用Heapsort按降序對List進行排序。而且我想用打印命令記錄我的計算,以便理解計算路徑。這是我的代碼工作:Python中按堆棧降序排列

def swap(a, i, j): 
    a[i], a[j] = a[j], a[i] 

def is_heap(a): 
    n = 0 
    m = 0 
    while True: 
     for i in [0, 1]: 
      m += 1 
      if m >= len(a): 
       return True 
      if a[m] > a[n]: 
       return False 
     n += 1 

def sift_down(a, n, max): 
    while True: 
     biggest = n 
     c1 = 2*n + 1 
     c2 = c1 + 1 
     for c in [c1, c2]: 
      if c < max and a[c] > a[biggest]: 
       biggest = c 
     if biggest == n: 
      return 
     swap(a, n, biggest) 
     n = biggest 

def heapify(a): 
    i = len(a)/2 - 1 
    max = len(a) 
    while i >= 0: 
     sift_down(a, i, max) 
     i -= 1 

def sortHeapDesc(a): 

    heapify(a) 
    j = len(a) - 1 
    while j > 0: 
     swap(a, 0, j) 
     sift_down(a, 0, j) 
     j -= 1 
    return a 

liste = [3, 2, 1, 9, 17, 4, -1, 0] 
heapResult= sortHeapDesc(liste) 
print (heapResult) 

而且我需要的就是這樣的結果是:17,9,4,3,2,1,0,-1]

+0

是不是有沒有使用Python文檔中提供的'heapsort'的原因? –

+0

@DmitryPolonskiy是的,我需要實現它的大學:)其作業考慮我的考試 –

回答

0

我sortHeapDesc功能是有點不同,但排序desc:

for i in range(start-1, 0, -1): # start -1 1 
    heapify(b, v, i) 

for i in range(v, -1, 1): # v-1 0 -1 
    chg(b, i, 0) 
    heapify(b, i, 0) 

看看兩個for-rows。該評論是針對asc並且進入目前正在執行的desc範圍內。如果你願意,我可以給你我完整的代碼。

問候。

+0

謝謝@Arne,但我有一個解決方案,它是在線變化2 < into > –